struct
is a keyword https://golang.org/ref/spec#Keywords在围棋中。它用于定义结构类型 https://golang.org/ref/spec#Struct_types,它是命名元素的序列。
例如:
type Person struct {
Name string
Age int
}
The struct{}
is a struct
具有零个元素的类型。当不需要存储信息时通常使用它。它的优点是大小为 0,因此通常不需要内存来存储类型的值struct{}
.
struct{}{}
另一方面是复合文字 https://golang.org/ref/spec#Composite_literals,它构造一个类型的值struct{}
。复合文字为结构、数组、映射和切片等类型构造值。其语法是类型后跟大括号中的元素。由于“空”结构(struct{}
) 没有字段,元素列表也是空的:
struct{} {}
| ^ | ^
type empty element list
作为示例,让我们在 Go 中创建一个“集合”。 Go 没有内置的集合数据结构,但它有内置的映射。我们可以将映射用作集合,因为映射最多只能有一个具有给定键的条目。由于我们只想在映射中存储键(元素),因此我们可以选择映射值类型为struct{}
.
一张地图string
要素:
var set map[string]struct{}
// Initialize the set
set = make(map[string]struct{})
// Add some values to the set:
set["red"] = struct{}{}
set["blue"] = struct{}{}
// Check if a value is in the map:
_, ok := set["red"]
fmt.Println("Is red in the map?", ok)
_, ok = set["green"]
fmt.Println("Is green in the map?", ok)
输出(尝试一下去游乐场 https://play.golang.org/p/zvQU9E6m6J):
Is red in the map? true
Is green in the map? false
但请注意,使用它可能会更方便bool
作为从映射创建集合时的值类型,因为检查元素是否在其中的语法更简单。详细信息请参见如何创建包含唯一字符串的数组? https://stackoverflow.com/questions/33207197/how-can-i-create-an-array-that-contains-unique-strings/33207265#33207265.