duanqun7761 2012-12-26 14:37
浏览 59
已采纳

Go中实现基本类型的接口

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?

  • 写回答

2条回答 默认 最新

  • dphw5101 2012-12-26 14:58
    关注

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法