Terminating statements
…
A “switch” statement in which:
- there are no “break” statements referring to the “switch” statement,
- there is a default case, and
- the statement lists in each case, including the default, end in a terminating statement, or a possibly labeled “fallthrough” statement.
This should make good sense, but let’s look at an example, and a counter-example, to illustrate.
func greet(args ...string) error {
switch len(args) {
case 0:
return errors.New("not enough arguments")
case 1:
fmt.Println("Hello", os.Args[1])
return nil
default:
return errors.New("too many arguments")
}
// <--- Notice, no return statement
}
In the above example, the switch statement meets all the requirements: No break
statement, there is a default
case, and each case ends in a terminating statement (a return
). AS a result, the switch
statement itself is a terminating statement, so no additional terminating statement is needed after.
A common alternative to this pattern is to omit the default case, in which case the switch
is no longer terminating:
func greet(args ...string) error {
switch len(args) {
case 0:
return errors.New("not enough arguments")
case 1:
fmt.Println("Hello", os.Args[1])
return nil
}
return errors.New("too many arguments")
}
In this case, the code is functionally equivalent, however. We’ve just moved the default case out of the switch
statement.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)