struct{} 和 struct{}{} 在 Go 中是如何工作的? [英] How do struct{} and struct{}{} work in Go?

查看:23
本文介绍了struct{} 和 struct{}{} 在 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 没有内置的 set 数据结构,但它有一个内置的 map.我们可以将地图用作集合,因为地图最多只能有一个具有给定键的条目.由于我们只想在地图中存储键(元素),我们可以选择地图值类型为 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)

输出(在 Go Playground 上试试):

Output (try it on the Go Playground):

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?.

这篇关于struct{} 和 struct{}{} 在 Go 中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆