Golang中struct{}{}的用法与注意事项

Golang中struct{}{}的用法与注意事项 查看更多 ljq@GitHub

  • struct {} struct {} 是一种没有元素的结构体类型,通常在不需要存储信息时使用。 优点:不需要内存来存储 struct{} 类型的值。

  • struct{}{} struct{}{} 是一个复合字面量,它构造了一个struct{} 类型的值,该值同样为空。

  • 两个 struct{}{} 的地址是相等的

package main

import "fmt"

type idBval struct {
Id int
}

func main() {
idA := struct{}{}
fmt.Printf("idA: %T and %v \n\n", idA, idA)

idB := idBval{
		1,
}
idB.Id = 2
fmt.Printf("idB: %T and %v \n\n", idB, idB)

idC := struct {
Id int
}{
		1,
}
fmt.Printf("idC: %T and %v \n\n", idC, idC)

mapD := make(map[string]struct{})
mapD["mapD"] = struct{}{}
_, ok := mapD["mapD"]
fmt.Printf("mapD['mapD'] is %v \n\n", ok)

sliceE := make([]interface{}, 2)
sliceE[0] = 1
sliceE[1] = struct{}{}
fmt.Printf("idE: %T and %v \n\n", sliceE, sliceE)

}

输出:


idA: struct {} and {}

idB: main.idBval and {2}

idC: struct {Id int} and {1}

mapD['mapD'] is true

idE: []interface {} and [1 {}]

查看更多 ljq@GitHub


更多关于Golang中struct{}{}的用法与注意事项的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中struct{}{}的用法与注意事项的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中,struct{}{}确实是一个特殊的空结构体值,常用于占位或信号传递。以下是具体用法和注意事项:

1. 作为map的占位符

最典型的用法是作为集合(set)的替代,利用map键的唯一性:

set := make(map[string]struct{})
set["key1"] = struct{}{}
set["key2"] = struct{}{}

// 检查元素是否存在
if _, exists := set["key1"]; exists {
    fmt.Println("key1 exists")
}

2. 通道信号传递

用于不需要传递数据的通道信号:

done := make(chan struct{})
go func() {
    time.Sleep(100 * time.Millisecond)
    done <- struct{}{}
}()

<-done // 等待信号,不关心传递的值
fmt.Println("done")

3. 方法接收器

当方法不需要访问结构体字段时:

type Noop struct{}

func (n Noop) Log() {
    fmt.Println("logging without state")
}

func main() {
    var n Noop
    n.Log()
}

4. 注意事项

  • 内存占用:所有struct{}{}值共享相同的内存地址
  • 类型相等性struct{}与包含字段的结构体类型不同
  • 序列化:JSON序列化时会被处理为null
// 地址验证
a := struct{}{}
b := struct{}{}
fmt.Println(&a == &b) // true

// 类型比较
type Empty struct{}
var e1 Empty
var e2 struct{}
// e1 = e2 // 编译错误:类型不匹配

5. 性能对比

与bool值对比的内存使用:

// bool map: 每个值占1字节
boolMap := make(map[string]bool)
boolMap["key"] = true

// struct{} map: 值不占内存
structMap := make(map[string]struct{})
structMap["key"] = struct{}{}

struct{}{}在Go中是零内存占用的占位符,特别适合需要语义明确且不关心值的场景。

回到顶部