background
When developing with Golang, it is often channel
used for signal notification, that is, the data passed has no real value in itself.
Method to realize
I have been using the following method before
ch := make(chan int)
Then I saw another way
ch := make(chan struct{})
Comparison of the two ways
Using empty struct
is a more memory-friendly development method. In the go
source code, for the empty struct
class data memory application part, the return address is a fixed address. Then possible memory abuse is avoided.
runtime/malloc.go :581
func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
...
if size == 0 {
return unsafe.Pointer(&zerobase)
}
...
// zerobase 是一个本 package 的局部变量
}
Notice
The point to note here is not size
to zero-value
confuse 0 with .
zero-value
The explanation is as follows
Variables declared without an explicit initial value are given their zero value.
默认值
and 占用内存空间为 0
is not a concept, examples are as follows
func main() {
array := [0]int{}
var a string
fmt.Printf("%d\n", unsafe.Sizeof(array))
fmt.Printf("%d\n", unsafe.Sizeof(a))
}
OutPut:
0
16
idea
It should be better to write the code like this in the future.
type notify struct{}
func main() {
ch := make(chan notify)
ch <- notify{}
}