Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What interfaces do basic types in go implement

Can you capture "a type that supports +, - * and /" with an interface? Or do you just have to use a typeswitch if you want to make a function on all number types?

like image 561
Thomas Ahle Avatar asked Nov 25 '25 12:11

Thomas Ahle


1 Answers

An interface defines a set of methods a type implements. In Go, basic types have no methods. The only interface they satisfy is the empty interface, interface{}.

If you wish to work on all number types, you can use a combination of reflect and type switches. If you use only type switches, you will have more code but it should be faster. If you use reflect, it will be slow but require much less code.

Please remember that in Go, it is very common that you don't attempt to make a function work on all numeric types. It is rarely necessary.

Type Switch Example:

func square(num interface{}) interface{} {
    switch x := num.(type) {
    case int:
        return x*x
    case uint:
        return x*x
    case float32:
        return x*x
    // many more numeric types to enumerate
    default:
        panic("square(): unsupported type " + reflect.TypeOf(num).Name())
    }
}

Reflect + Typeswitch Example:

func square(num interface{}) interface{} {
    v := reflect.ValueOf(num)
    ret := reflect.Indirect(reflect.New(v.Type()))

    switch v.Type().Kind() {
    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
        x := v.Int()
        ret.SetInt(x * x)
    case reflect.Uint, reflect.Uintptr, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
        x := v.Uint()
        ret.SetUint(x * x)
    case reflect.Float32, reflect.Float64:
        x := v.Float()
        ret.SetFloat(x * x)
    default:
        panic("square(): unsupported type " + v.Type().Name())
    }

    return ret.Interface()
}
like image 189
Stephen Weinberg Avatar answered Nov 27 '25 15:11

Stephen Weinberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!