【问题标题】:What interfaces do basic types in go implementgo中的基本类型实现了哪些接口
【发布时间】:2012-12-12 02:22:55
【问题描述】:

你能用接口捕获“支持+、-*和/的类型”吗?或者,如果您想对所有数字类型进行函数处理,是否只需要使用类型开关?

【问题讨论】:

    标签: types interface numbers go


    【解决方案1】:

    接口定义了一个类型实现的一组方法。在 Go 中,基本类型没有方法。他们唯一满足的接口是空接口interface{}。

    如果您希望处理所有数字类型,可以结合使用反射和类型开关。如果您只使用类型开关,您将有更多的代码,但它应该更快。如果你使用反射,它会很慢,但需要更少的代码。

    请记住,在 Go 中,您通常不会尝试使函数适用于所有数字类型。很少需要。

    类型切换示例:

    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 示例:

    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()
    }
    

    【讨论】:

    • 对,显然在第一个 typeswitch 示例中对术语进行分组并没有帮助
    【解决方案2】:

    预声明的类型没有附加任何方法。

    算术运算符可以声明为某个接口的方法集,但只能声明为例如。方法“添加”、“子”等,即。没有办法重新定义多态 '+', '-', ... 运算符的作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      相关资源
      最近更新 更多