Types go中的基本类型实现哪些接口
您能用接口捕获“支持+、-*和/”的类型吗?或者,如果要在所有数字类型上创建函数,是否只需使用类型开关?接口定义类型实现的一组方法。在Go中,基本类型没有方法。他们满足的唯一接口是空接口,Types go中的基本类型实现哪些接口,types,interface,numbers,go,Types,Interface,Numbers,Go,您能用接口捕获“支持+、-*和/”的类型吗?或者,如果要在所有数字类型上创建函数,是否只需使用类型开关?接口定义类型实现的一组方法。在Go中,基本类型没有方法。他们满足的唯一接口是空接口,interface{} 如果希望处理所有数字类型,可以使用反射和类型开关的组合。如果只使用类型开关,代码会更多,但速度应该更快。如果使用reflect,速度会很慢,但需要的代码要少得多 请记住,在Go中,不尝试使函数在所有数字类型上工作是很常见的。很少有必要这样做 类型开关示例: func square(num
interface{}
如果希望处理所有数字类型,可以使用反射和类型开关的组合。如果只使用类型开关,代码会更多,但速度应该更快。如果使用reflect,速度会很慢,但需要的代码要少得多
请记住,在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())
}
}
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()
}
反射+类型开关示例:
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())
}
}
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()
}
预声明的类型没有附加任何方法
算术运算符可以声明为某些接口的方法集,但只能声明为方法“Add”、“Sub”等,即无法重新定义多态性“+”、“-”、。。。是的 对,很明显,在第一个typeswitch示例中,对术语进行分组并没有帮助