#generic function without type switch?

15 messages · Page 1 of 1 (latest)

indigo narwhal
#

I have this code:

func numToByte(v any) (byte, error) {
    switch v := v.(type) {
    case int:
        if(v > 255) {
            return 0, errors.New("must be less than 255");
        }
        return byte(v), nil
    case float64:
        if(v > 255) {
            return 0, errors.New("must be less than 255");
        }
        return byte(v), nil
    default:
        return 0, errors.New("must be number")
    }
}

Can I make it less redundant?

uneven arrow
#
func numToByte[T ~int | ~int16 | ~int32 | ~int64 | constraints.Unsigned | constraints.Float](v T) (byte, error) {
    if v > 255 {
        return 0, errors.New("must be less than 255")
    }
    return byte(v), nil
}
#

we can't use constraints.Integer because that includes int8 which cannot represent 255

indigo narwhal
uneven arrow
#

well no, because then you're right back at your original code

indigo narwhal
#

But I can't not use that switch?

uneven arrow
#

if you don't know what type the incoming variable has at compile time you need to check it at runtime

#

which involves that switch

#

no way around it

indigo narwhal
#

ight, thanks

indigo narwhal
# uneven arrow no way around it

some operations, like > and byte() should work on both int and float64, right? Is there a reason case int, float64: doesn't allow that?

uneven arrow
#

the switch machinery was introduced far before generics, it was there from the beginning of the language

#

before generics, there wasn't really a way to say "this type supports the operations from the intersection of these types"

#

so the spec simply says that for a type switch with multiple types in one case, the variable goes to any

indigo narwhal
#

ah, okay