Go 中的空结构:它们的用途和应用
Go 提供了一个独特的空结构(struct{})功能。这些零大小的结构具有独特的特征,使它们在各种场景中都很有价值。
空结构的好处
使用示例
import "sync" var wg sync.WaitGroup func notify() { wg.Done() } func main() { wg.Add(1) go notify() wg.Wait() }
import ( "fmt" "testing" ) type SomeInterface interface { DoSomething() } type Empty struct{} func (e Empty) DoSomething() { fmt.Println("Doing something") } func Test(t *testing.T) { var i SomeInterface = Empty{} i.DoSomething() }
type Set[T comparable] map[T]struct{} func NewSet[T comparable](s []T) Set[T] { set := make(Set[T], len(s)) for _, v := range s { set[v] = struct{}{} } return set }
以上是Go中空结构体的好处和应用是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!