【发布时间】:2017-12-20 17:33:43
【问题描述】:
我想知道 Go 中的“struct{}”和“struct{}{}”是什么意思?一个例子如下:
array[index] = struct{}{}
或
make(map[type]struct{})
【问题讨论】:
我想知道 Go 中的“struct{}”和“struct{}{}”是什么意思?一个例子如下:
array[index] = struct{}{}
或
make(map[type]struct{})
【问题讨论】:
struct 是 Go 中的 keyword。用于定义struct types,即命名元素的序列。
例如:
type Person struct {
Name string
Age int
}
struct{} 是具有零个元素的 struct 类型。它通常在不需要存储信息时使用。它的好处是大小为 0,因此通常不需要内存来存储 struct{} 类型的值。
另一方面,struct{}{} 是一个composite literal,它构造了一个struct{} 类型的值。复合文字为结构、数组、映射和切片等类型构造值。它的语法是大括号中的元素后跟的类型。由于“空”结构 (struct{}) 没有字段,因此元素列表也是空的:
struct{} {}
| ^ | ^
type empty element list
作为一个例子,让我们在 Go 中创建一个“集合”。 Go 没有内置的 set 数据结构,但它有一个内置的 map。我们可以将地图作为一个集合使用,因为地图最多只能有一个带有给定键的条目。并且由于我们只想在 map 中存储键(元素),我们可以选择 map 值类型为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)
输出(在Go Playground上试试):
Is red in the map? true
Is green in the map? false
请注意,在从映射中创建集合时,使用bool 作为值类型可能更方便,因为检查元素是否在其中的语法更简单。详情请见How can I create an array that contains unique strings?。
【讨论】:
正如izca所指出的:
Struct 是一个 go 关键字,用于定义结构类型,这些类型只是用户定义的类型,由您决定的任意类型的变量组成。
type Person struct {
Name string
Age int
}
结构也可以为空,元素为零。 但是 Struct{}{} 有不同的含义。这是一个复合结构文字。它内联定义了一个结构类型并定义了一个结构并且不分配任何属性。
emptyStruct := Struct{} // This is an illegal operation
// you define an inline struct literal with no types
// the same is true for the following
car := struct{
Speed int
Weight float
}
// you define a struct be do now create an instance and assign it to car
// the following however is completely valid
car2 := struct{
Speed int
Weight float
}{6, 7.1}
//car2 now has a Speed of 6 and Weight of 7.1
这里的这一行只是创建了一个完全合法的空结构文字映射。
make(map[type]struct{})
和
一样make(map[type]struct{
x int
y int
})
【讨论】: