Today I’ll be live coding again. I hope you can join, and ask your Go-related questions as I continue to hack away on my open-source project, using TDD. Catch the stream on YouTube.
Have you ever tried to explain an “if” statement in as few words as possible? It’s such a simple concept, that I don’t think I’ve ever bothered trying to explain it.
Well, today’s section of the Go spec does explain it. And I have to say, I think it does an admirable job.
If statements
“If” statements specify the conditional execution of two branches according to the value of a boolean expression. If the expression evaluates to true, the “if” branch is executed, otherwise, if present, the “else” branch is executed.
I suppose in my head, an if
statement is separate from an else
, and this would lead to some confusion in trying to explain the concept. But I like this explanation. By framing it as either executing one branch or the other, it’s quite simple. Then the second branch (the one prefaced by else
) is made optional.
IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
if x > max { x = max }
Relative to some other languages, that have elseif
, Go makes this very simple and straight forward. Although one might wonder how to handle the else
… if
case in Go. Well, you just do it like that:
if thing == 1 {
/* ... */
} else if thing == 2 {
/* ... */
} else if thing == 3 {
/* ... */
}
This is roughly equivalent to:
if thing == 1 {
/* ... */
} else {
if thing == 2 {
/* ... */
} else {
if thing == 3 {
/* ... */
}
}
}
And I think when you consider it this way, it’s pretty intuitive, and removes whatever mystery might exist by thinking of if
as a combination of if
, else
, and elseif
interactions.
The expression may be preceded by a simple statement, which executes before the expression is evaluated.
if x := f(); x < y { return x } else if x > z { return z } else { return y }
I’m sure you’ve seen these simple statements before; they’re allowed with certain if
, select
, and switch
statements. They let you do a little pre-computation, within the scope of that statement. That is to say, that the following are roughly equivalent, in terms of variable scoping:
if x := f; x < y {
return x
}
{
x := f
if x < y {
return x
}
}
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)