我想知道在Go语言中"struct{}"和"struct{}{}"代表什么意思?下面是一个例子:
。
array[index] = struct{}{}
或者make(map[type]struct{})
struct
是Go语言中的关键字。它用于定义结构类型,这是一系列命名元素的序列。
例如:
type Person struct {
Name string
Age int
}
struct{}
是一个零元素的结构体类型。通常在不需要存储任何信息时使用它。它的好处是大小为0,因此通常不需要内存来存储类型为struct{}
的值。struct{}{}
是一个复合字面量,它构造了一个类型为struct{}
的值。复合字面量可以为诸如结构体、数组、映射和切片等类型构造值。它的语法是类型后跟大括号中的元素。由于“空”结构体(struct{}
)没有字段,因此元素列表也为空: struct{} {}
| ^ | ^
type empty element list
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 作为值类型可能更方便,因为检查元素是否在其中的语法更简单。有关详细信息,请参见如何创建包含唯一字符串的数组?。
正如 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
})