if and else
Go's if statement is simpler than what you may have used in other languages. No parentheses around the condition, always braces around the body, and no implicit conversion of numbers or strings into truth values. Everything else will look familiar.
n := 10
if n > 0 {
fmt.Println("positive")
}
The condition goes right after if, the body goes in braces on the next line.
Chaining with else if and else
Add as many branches as you need with else if, and fall back to else for anything not caught earlier:
n := 0
if n > 0 {
fmt.Println("positive")
} else if n < 0 {
fmt.Println("negative")
} else {
fmt.Println("zero")
}
Only the first matching branch runs. Once a branch has handled the value, the rest are skipped.
Conditions must be booleans
Go will not treat a non-zero integer or a non-empty string as "true" the way C and JavaScript do. The condition has to be an actual bool:
n := 1
if n { // compile error: non-bool n (type int) as if condition
fmt.Println("set")
}
if n != 0 { // fine
fmt.Println("set")
}
The same rule applies to strings. if s { ... } where s is a string is a compile error; you write if s != "" { ... }. Go makes you say what you actually mean.
Braces are mandatory, and stay on the same line
Go has no one-line if like C's if (x) foo();. The body always goes in braces. The opening brace must also sit on the same line as if:
if n > 0 {
fmt.Println("positive")
}
if n > 0 // compile error: syntax error
{
fmt.Println("positive")
}
This is a consequence of Go's automatic semicolon insertion. Ending a line after if n > 0 tells the parser the statement is complete, and the next line's { has nothing to attach to. Keep the brace next to if and the parser stays happy.
Try this out: open the starter, move the { from the same line as if n > 0 down onto its own line:
if n > 0
{
fmt.Println("positive")
}
Run it. You'll get a syntax error. Put the { back on the same line as if to recover. This is the single most common "weird error" that trips people coming from C-family languages, worth seeing once so you recognise it later.
One more thing if can do: declare a small variable right before the condition. This is useful when the condition needs to compute something that you want to reuse in the body:
if n := compute(); n > 0 {
// n is visible here, and holds the value returned by compute()
fmt.Println("positive", n)
}
// n is not visible here
That short-statement form is the shape you will see in most real Go code, and it gets its own lesson next.
The starter already declares n := 17. Add two blocks:
- An
if / else if / elsechain that prints"positive","negative", or"zero"based on the sign ofn. - An
if / elsethat prints"even"or"odd"based on whethernis divisible by2.
positive odd