Terminating statements
…
A “select” statement in which:
- there are no “break” statements referring to the “select” statement, and
- the statement lists in each case, including the default if present, end in a terminating statement.
This is quite similar to the “switch” case we looked at yesterday. Let’s consider an example:
select {
case <-ctx.Done():
return ctx.Err()
case msg := <-messageChannel
fmt.Println(message)
return nil
}
This select
statement has two cases, each of which terminates (by virtue of returning). So the select statement itself is terminating—any code that follows this statement in the same block, would never execute.
What if we want to continue reading messages from the messageChannel
channel until all messages are consumed?
for {
select {
case <-ctx.Done():
return ctx.Err()
case msg, ok := <-messageChannel
if !ok {
return nil
}
fmt.Println(message)
}
}
Now the select
statement is no longer terminating, because the second case doesn’t (always) return. But we’ve wrapped it in an infinite for
loop, however, is a terminating statement, as we saw earlier.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)