我该如何构建一个通用结构体呢?
我尝试了:
type SafeSet[type T] struct {
Values map[T]bool
}
我想能够做例如:
SafeSet{ Values: make(map[net.Conn]bool) }
SafeSet{ Values: make(map[string] bool) }
SafeSet{ Values: make(map[int] bool) }
您无法在当前的 Go 版本 1.17 中完成此操作。不幸的是,没有其他可以说的了。
type SafeSet[T comparable] struct {
Values map[T]bool
}
特别地:
T
之后T
用作映射键,则必须使用内置的约束comparable
,因为映射键必须是可比较的,即支持==
运算符。然后,您必须使用实际类型参数实例化参数化类型:
示例:
要使用通用类型,您必须提供类型参数。这称为实例化。类型参数像往常一样出现在方括号中。当我们通过为类型参数提供类型参数来实例化类型时,在类型定义中使用类型参数的每个使用都将替换为相应的类型参数。
s0 := SafeSet[net.Conn]{Values: make(map[net.Conn]bool)}
s1 := SafeSet[string]{Values: make(map[string]bool)}
s2 := SafeSet[int]{Values: make(map[int]bool)}
由于实例化 SafeSet
字面量有些冗长,您可以使用通用的构造函数:
func NewSafeSet[T comparable]() SafeSet[T] {
return SafeSet[T]{Values: make(map[T]bool)}
}
s3 := NewSafeSet[uint64]()
s3.Values[200] = true
Gotip 游乐场: https://gotipplay.golang.org/p/Qyd6zTLdkRn
SafeSet
吗? - Sebastian Nielsendatabase/sql
中的NullXxx
类型。 - mkopriva