因为我对2种不同的数据类型有类似的功能:
func GetStatus(value uint8) (string) {...}
func GetStatus(name string) (string) {...}
我想使用更简单的方式:
func GetStatus(value interface{}) (string) {...}
是否可以使用界面创建通用功能?
可以使用reflect.Typeof(value)
答案 0 :(得分:2)
您想要做的是否需要reflect
包的复杂性和开销?您是否考虑过简单的switch
声明type
切换?
package main
import (
"fmt"
)
func GetStatus(value interface{}) string {
var s string
switch v := value.(type) {
case uint8:
v %= 85
s = string(v + (' ' + 1))
case string:
s = v
default:
s = "error"
}
return s
}
func main() {
fmt.Println(GetStatus(uint8(2)), GetStatus("string"), GetStatus(float(42.0)))
}