In golang, when we need to wait for something to finish, we will use a channel.
example:
done := make(chan struct{})
go func() {
// ...
close(done)
}()
<-done
But, in other way, chan interface{}
also works in this case.
So, what's the difference between chan struct{}
and chan interface{}
?
Example2:
done := make(chan struct{})
go func() {
// ...
done <- struct{}{}
}()
<- done
In other case, if don't close channel in goroutine instead of send object to it.
There will create an object in goroutine, but if using chan interface{}
, can be send nil
object to channel.
Is it better to use chan struct{}
?
Go channels are used for communicating between concurrently running functions by sending and receiving a specific element type's data. When we have numerous Goroutines running at the same time, channels are the most convenient way for them to communicate with one another.
Signaling channel with chan struct{} Sometimes you don't want to send a value over a channel but use it only as a way to signal an event. In those cases use chan struct{} to document the fact that the value sent over a channel has no meaning. Signaling channel is often used as a way to tell goroutines to finish.
Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.
We can close a channel in Golang with the help of the close() function. Once a channel is closed, we can't send data to it, though we can still read data from it. A closed channel denotes a case where we want to show that the work has been done on this channel, and there's no need for it to be open.
In your example of a 'done' channel, functionally speaking, the channel can be of literally any type, since no data is actually sent, and the channel is just used as a signaling mechanism. But in the interest of memory utilization, struct{}
is the smallest data type available in Go, since it contains literally nothing, so no allocation necessary, which is why it's typically used in such scenarios.
The empty struct struct {}
requires no memory. So if you have a channel with a large capacity you can save a few bytes by switching from make(chan bool, 1<<16)
to make(struct {}, 1<<16)
. Using interface {} requires more space and is really strange here.
For an unbuffered done channel I think using struct {} is wrong as it is unclear. Using a simple chan bool
is much more sensible. Using interface {} is completely wrong: It probably uses more space and is even less clear than struct {}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With