Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which channel type should be used when the message is never evaluated?

Tags:

go

With the following select statement I want to ensure that some none-blocking function is only executed one by one:

select {
case <-available:
default:
    fmt.Println("busy")
    return
}
go func() {
    defer func() { available <- true }()
    doSomethingOneByOne()
}()

Currently I'm using bool as a channel type and it works as expected.

What I don't like is that using bool suggests that it matters if the value is true or false. But actually it doesn't matter in this case. In my opinion this makes understanding the code a bit harder because it is misleading.

Is there a convention for which type to use when the value doesn't matter?

like image 215
yaccob Avatar asked Feb 02 '19 11:02

yaccob


1 Answers

chan struct{} is a valid choice — struct{} is a valid type, but a value of this type contains no data and has zero size, and all struct{} values are indistinguishable, making it a unit type for Go. To construct a value of type struct{} to send on the channel, you can use the literal struct{}{}.

like image 156
hobbs Avatar answered Sep 29 '22 17:09

hobbs