type MyNumber interface {
float32, float64, uint, int // this is not supported
}
func PrintNumber(n MyNumber) {
switch n.(type) {
case float32, float64, uint, int:
fmt.Printf("%v\n", n)
default:
panic("PrintNumber only supports types float32, float64, uint, int")
}
}
在go中,可以定义一个空白接口(interface),基本上允许任何类型
var v interface{}
v = "string"
v = 0.1
有没有办法将允许的类型减少到特定的类型列表?
就像是
type MyNumber float32, float64, uint, int
或者
type MyNumber interface {
float32, float64, uint, int
}
这样我就可以让编译器检查函数是否支持该类型。
最佳答案
Is there a way to reduce the allowed types to a specific list of types [of an empty interface]?
在编译时,没有。
但是,您可以选择在运行时使用限制。当有其他选择时,应该避免这种情况,因为它不能提供足够的安全性。
这是在标准库中的许多地方完成的,例如 json marshaler,它需要一个指针作为目标。
关于go - go 支持多类型吗? (泛型类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60912573/