空结构体struct{}用途
golang 空结构体 struct{} 可以用来节省内存
a := struct{}{}
println(unsafe.Sizeof(a))
// Output: 0
空struct{}也在向别人表明,这里并不需要一个值
在map里节省资源
set := make(map[string]struct{})
for _, value := range []string{"apple", "orange", "apple"} {
set[value] = struct{}{}
}
fmt.Println(set)
// Output: map[orange:{} apple:{}]
向人展示对象中不需要任何数据,仅包含需要方法。在调用也并无任何区别
type Lamp struct{}
func (l Lamp) On() {
println("On")
}
func (l Lamp) Off() {
println("Off")
}
func main() {
// Case #1.
var lamp Lamp
lamp.On()
lamp.Off()
// Output:
// on
// off
// Case #2.
Lamp{}.On()
Lamp{}.Off()
// Output:
// on
// off
}
用于传递信号的channel
func worker(ch chan struct{}) {
// Receive a message from the main program.
<-ch
println("roger")
// Send a message to the main program.
close(ch)
}
func main() {
ch := make(chan struct{})
go worker(ch)
// Send a message to a worker.
ch <- struct{}{}
// Receive a message from the worker.
<-ch
println(“roger")
// Output:
// roger
// roger
}
Struct能不能比较
总结:
1.数据类型的可排序、可比较和不可比较
- 可排序的数据类型有三种,Integer,Floating-point,和String
- 可比较的数据类型除了上述三种外,还有Boolean,Complex,Pointer,Channel,Interface和Array
- 不可比较的数据类型包括,Slice, Map, 和Function
2.对于同一个struct的不同实例:
- 值类型的实例,不包含不可比较类型,势力之间可以比较
- 值类型的实例,如果包含了不可比较类型,实例之间即使赋值相同,仍不可比较
- 指针类型实例之间可以比较(指针类型前面加*,表示指针指向的值,即结构体实例,不能用==)
3.对于两个不同struct实例:
- 不同的结构体,但可以强制转换,所以强转之后可以比较
- 如果成员变量含有不可比较成员变量,即使可以强制转换,也不可以比较
4.struct可以作为map的key吗
- struct必须是可比较的,才能作为key,否则编译时报错