如何构建通用结构?
我试过:
type SafeSet[type T] struct {
Values map[T]bool
}
Run Code Online (Sandbox Code Playgroud)
我希望能够做到例如
SafeSet{ Values: make(map[net.Conn]bool) }
SafeSet{ Values: make(map[string] bool) }
SafeSet{ Values: make(map[int] bool) }
Run Code Online (Sandbox Code Playgroud)
当前的 Go 版本 1.17 无法做到这一点。不幸的是,没有什么可说的。
\n在将泛型添加到语言中之后,可能在 Go 1.18(2022 年初)中,根据当前接受的提案,这种参数化类型的语法将是:
\ntype SafeSet[T comparable] struct {\n Values map[T]bool\n}\nRun Code Online (Sandbox Code Playgroud)\n尤其:
\nTT映射键,则必须使用内置约束comparable,因为映射键必须是可比较的 \xe2\x80\x94 即支持==运算符。然后,您必须使用实际类型参数实例化参数化类型:
\n例子:
\n\n\n要使用泛型类型,您必须提供类型参数。这称为实例化。像往常一样,类型参数出现在方括号中。当我们通过为类型参数提供类型参数来实例化类型时,我们会生成一个类型,其中类型定义中类型参数的每次使用都被相应的类型参数替换。
\n
s0 := SafeSet[net.Conn]{Values: make(map[net.Conn]bool)}\n s1 := SafeSet[string]{Values: make(map[string]bool)}\n s2 := SafeSet[int]{Values: make(map[int]bool)}\nRun Code Online (Sandbox Code Playgroud)\n由于实例化SafeSet文字看起来有点冗长,因此您可以使用通用构造函数:
func NewSafeSet[T comparable]() SafeSet[T] {\n return SafeSet[T]{Values: make(map[T]bool)}\n}\nRun Code Online (Sandbox Code Playgroud)\n显然,语法是相同的,只是在这种情况下,您使用 arg 类型显式实例化该函数:
\n s3 := NewSafeSet[uint64]()\n s3.Values[200] = true\nRun Code Online (Sandbox Code Playgroud)\nGotip 游乐场:https://gotipplay.golang.org/p/Qyd6zTLdkRn
\n| 归档时间: |
|
| 查看次数: |
6934 次 |
| 最近记录: |