我尝试从设计草案(泛型的下一步) 中运行示例go2go.playground
type Pair(type T) struct { f1, f2 T }
,但得到一个错误
prog.go2:14:11: expected type, found 'type' (and 1 more errors)
我在哪里可以找到实际的go generics
design draft
?
我尝试从设计草案(泛型的下一步) 中运行示例go2go.playground
type Pair(type T) struct { f1, f2 T }
,但得到一个错误
prog.go2:14:11: expected type, found 'type' (and 1 more errors)
我在哪里可以找到实际的go generics
design draft
?
您正在查看过时的设计草案。
这是最新的:https ://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md
所以,它不是:
type Pair(type T) struct { f1, f2 T }
但:
type Pair[T any] struct { f1, f2 T }
这是几周前以来的旧语法。尝试
type Pair[T any] struct { f1, f2 T }
请注意,现在使用方括号代替圆括号,并且type
不再使用关键字。您还必须使用any
约束,而以前如果对类型参数没有限制,则可以不使用约束。
顺便说一句,通常Pair
指的是具有 2 个不同类型的 2 个字段的结构,例如type Pair[T1, T2 any] struct { first T1; second T2 }
有关构建的示例代码,请参见go2go Playground。
如 2019 年设计草案第一段所述,新草案为https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md