Why using `chan struct{}` when wait something done not `chan interface{}`?

Viewed 13739

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{}?

2 Answers

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 {}.

Related