Go中的struct {}和struct {} {}如何工作? [英] How do struct{} and struct{}{} work in Go?
问题描述
我想知道Go中的"struct {}"和"struct {} {}"是什么意思?一个例子如下:
I am wondering what does "struct{}" and "struct{}{}" mean in Go? An example is as follows:
array[index] = struct{}{}
或
make(map[type]struct{})
推荐答案
struct
是关键字在Go中.它用于定义结构类型,该结构类型是一系列命名元素.
struct
is a keyword in Go. It is used to define struct types, which is a sequence of named elements.
例如:
type Person struct {
Name string
Age int
}
struct{}
是具有零个元素的struct
类型.通常在不存储任何信息时使用.它具有大小为0的优点,因此通常不需要内存来存储类型为struct{}
的值.
The struct{}
is a struct
type with zero elements. It is often used when no information is to be stored. It has the benefit of being 0-sized, so usually no memory is required to store a value of type struct{}
.
struct{}{}
是复合文字,它构造了一个类型的值struct{}
.复合文字为诸如结构,数组,映射和切片之类的类型构造值.它的语法是大括号后跟元素的类型.由于空"结构(struct{}
)没有字段,因此元素列表也为空:
struct{}{}
on the other hand is a composite literal, it constructs a value of type struct{}
. A composite literal constructs values for types such as structs, arrays, maps and slices. Its syntax is the type followed by the elements in braces. Since the "empty" struct (struct{}
) has no fields, the elements list is also empty:
struct{} {}
| ^ | ^
type empty element list
作为示例,让我们在Go中创建一个集合". Go没有内置的集合数据结构,但是它具有内置的映射.我们可以将地图用作集合,因为一张地图最多只能有一个具有给定键的条目.并且由于我们只想在地图中存储键(元素),因此我们可以选择地图值类型为struct{}
.
As an example let's create a "set" in Go. Go does not have a builtin set data structure, but it has a builtin map. We can use a map as a set, as a map can only have at most one entry with a given key. And since we want to only store keys (elements) in the map, we may choose the map value type to be 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)
输出(在转到操场上尝试):
Is red in the map? true
Is green in the map? false
请注意,但是,在地图外创建集合时,使用bool
作为值类型可能更方便,因为检查元素中是否包含元素的语法更简单.有关详细信息,请参见如何创建包含唯一字符串的数组?.
Note that however it may be more convenient to use bool
as the value type when creating a set out of a map, as the syntax to check if an element is in it is simpler. For details, see How can I create an array that contains unique strings?.
这篇关于Go中的struct {}和struct {} {}如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!