在Go语言中,struct{}和struct{}{}是什么意思?

28
我想知道在Go语言中"struct{}"和"struct{}{}"代表什么意思?下面是一个例子:

array[index] = struct{}{}
或者
make(map[type]struct{})

使用Go语言中的结构体将Map用作集合,其性能是否原因。 - user3025289
2个回答

45

struct是Go语言中的关键字。它用于定义结构类型,这是一系列命名元素的序列。

例如:

type Person struct {
    Name string
    Age  int
}
struct{} 是一个零元素的结构体类型。通常在不需要存储任何信息时使用它。它的好处是大小为0,因此通常不需要内存来存储类型为struct{}的值。
另一方面,struct{}{} 是一个复合字面量,它构造了一个类型为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)

输出(在Go Playground上尝试):
Is red in the map? true
Is green in the map? false

请注意,当从地图创建一个集合时,使用 bool 作为值类型可能更方便,因为检查元素是否在其中的语法更简单。有关详细信息,请参见如何创建包含唯一字符串的数组?

11

正如 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
     })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接