Last week we saw that a block that ends in a terminaging statement is itself a terminating statement.
Today we expand a bit on that idea:
Terminating statements
…
An “if” statement in which:
- the “else” branch is present, and
- both branches are terminating statements.
In other words, the following counts as a terminating statement:
if somethingInterestingHappened() {
fmt.Println("Wow, that was interesting!")
return
} else {
fmt.Println("That was boring.")
return
}
Both branches of the if
statement terminate, so the statement as a whole is a terminating statement. Put another way: There’s no possible way any code following this block would be executed, therefore it is terminating.
What would make this not-terminating?
- Obviously, if we remove either
return
statement - If the
else
were replaced with anelse if
- If we add some statement to either block that breaks out of otherwise normal flow control (such as a
goto
,continue
, orbreak
—assuming, of course, this code is part of a relevant loop or select statement.)
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)