Hua*_*Wei 20 generics constraints go type-parameter
type Number interface {
int | int64 | float64
}
type NNumber interface {
}
//interface contains type constraints
//type NumberSlice []Number
type NNumberSlice []NNumber
func main() {
var b interface{}
b = interface{}(1)
fmt.Println(b)
// interface contains type constraints
// cannot use interface Number in conversion (contains specific type constraints or is comparable)
//a := []Number{Number(1), Number(2), Number(3), Number(4)}
//fmt.Println(a)
aa := []interface{}{interface{}(1), interface{}(2), interface{}(3), 4}
fmt.Println(aa)
aaa := []NNumber{NNumber(1), NNumber(2), NNumber(3), 4}
fmt.Println(aaa)
}
Run Code Online (Sandbox Code Playgroud)
为什么Number切片a不能像这样初始化?
NumberSlice看起来NNumberSlice很相似,但是类型约束是什么意思,语法看起来很奇怪
bla*_*een 25
语言规范明确禁止将带有类型元素的接口用作类型参数约束之外的任何内容(引用位于“接口类型”段落下):
非基本接口只能用作类型约束,或者用作用作约束的其他接口的元素。它们不能是值或变量的类型,也不能是其他非接口类型的组件。
嵌入的接口comparable或其他非基本接口也是非基本的。您的Number界面包含一个联合,因此它也是非基本的。
举几个例子:
// basic: only methods
type A1 interface {
GetName() string
}
// basic: only methods and/or embeds basic interface
type B1 interface {
A1
SetValue(v int)
}
// non-basic: embeds comparable
type Message interface {
comparable
Content() string
}
// non-basic: has a type element (union)
type Number interface {
int | int64 | float64
}
// non-basic: embeds a non-basic interface
type SpecialNumber interface {
Number
IsSpecial() bool
}
Run Code Online (Sandbox Code Playgroud)
在变量的初始化中a,您试图Number在类型转换中使用Number(1),这是不允许的。
您只能用作Number类型参数约束,即限制泛型类型或函数实例化所允许的类型。例如:
type Coordinates[T Number] struct {
x, y T
}
func sum[T Number](a, b T) T {
return a + b
}
Run Code Online (Sandbox Code Playgroud)