Today’s live stream is starting an hour later than usual. Join me at 16:00, CEST, for some live Go coding using TDD.
Terminating statements
…
- A labeled statement labeling a terminating statement.
Labeled statement’s are not used a lot in Go. Terminating labeled statements even less so. But they do exist, just the same. Here’s an example, using goto
, and a labeled terminating statement.
func foo() {
if someCondition {
goto end
}
fmt.Println("unf")
end:
return
}
Here end
is a label, that labels the statement return
. Since the label labels a terminating statement, the labeled statement terminates. Funny how that works.
Can we have a labeled terminating statement that isn’t the target of goto
?
Well, labels can be the target of goto
, break
, or continue
. We already saw an example of goto
. So what about the others?
A break
can only ever be referred to from within for
loops or select
or switch
statements, and adding a break
to any of these renders the block that contains it no longer terminating.
So that leaves continue
. continue
can reference a terminating statement, if the loop it’s in is terminating:
loop:
for {
continue loop
}
Silly example of an infinite loop, but it is terminating.
Here’s a plausibly more realistic example:
var i int
loop:
for {
i++
if i > 10 {
return
}
continue loop
}
Obviously using continue
in both of these examples is silly, as that would be the default behavior anyway. But I trust you can imagine that there’s some other logic to make the use of continue
meaningful.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)