我想知道 Go 中的“struct{}”和“struct{}{}”是什么意思?示例如下:
array[index] = struct{}{}
或
make(map[type]struct{})
最佳答案
struct
是一个 keyword在去。它用于定义 struct types ,这是一个命名元素的序列。
例如:
type Person struct {
Name string
Age int
}
struct{}
是具有零个元素的 struct
类型。它通常在不需要存储信息时使用。它的优点是大小为 0,因此通常不需要内存来存储 struct{}
类型的值。
struct{}{}
另一方面是一个 composite literal ,它构造一个 struct{}
类型的值。复合文字为结构、数组、映射和 slice 等类型构造值。它的语法是类型后跟大括号中的元素。由于“空”结构 (struct{}
) 没有字段,因此元素列表也是空的:
struct{} {}
| ^ | ^
type empty element list
例如,让我们在 Go 中创建一个“集合”。 Go 没有内置的集合数据结构,但它有一个内置的映射。我们可以将 map 用作一个集合,因为 map 最多只能有一个具有给定键的条目。由于我们只想在 map 中存储键(元素),我们可以选择 map 值类型为 struct{}
。
包含string
元素的 map :
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? .
关于go - struct{} 和 struct{}{} 在 Go 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45122905/