Today we’ll talk about labeled statements, which we’ve just recently mentioned in the context of terminating statements.
Labeled statements
A labeled statement may be the target of a
goto
,break
orcontinue
statement.LabeledStmt = Label ":" Statement . Label = identifier .
Error: log.Panic("error encountered")
If I may say so, the example provided is pretty bad. I mean, yeah, it technically is a labeled statement. It contains the label Error
, followed by a colon (:
), followed by a statement. But that’s it.
And in fact, if you try to run that code alone, it won’t even work, complaining “label Error defined and not used”.
So let me do my own expansion, with what is probably the most common use of a labeled statement: Breaking out of the outter loop in a nested loop.
For this example, let’s say we’re looking through a list of words to find the first one that contains the letter a
. And we’re going to do it manually, for the purpose of demonstration, rather than relying on something like strings.Contains
.
var words = []string{"cow", "bird", "cat", "canary"}
for _, word := range words {
for _, letter := range word {
if letter == 'a' {
fmt.Printf("%q is the first word to contain 'a'\n", word)
break
}
}
}
Let’s run this nifty program now and… oh, oops! Our output is:
"cat" is the first word to contain 'a'
"canary" is the first word to contain 'a'
Why?
Becuase the break
statement breaks out of the inner for loop, not the outter one. To break out of the outter loop, we need a label. Let’s add one:
var words = []string{"cow", "bird", "cat", "canary"}
Outer:
for _, word := range words {
for _, letter := range word {
if letter == 'a' {
fmt.Printf("%q is the first word to contain 'a'\n", word)
break Outer
}
}
}
Now we get the output we want:
"cat" is the first word to contain 'a'
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)