If and Else
You already know what if does. What's worth learning is how Go's version
differs from the C family's — two small grammar changes that quietly prevent
whole categories of bugs.
No parentheses, braces required
The condition takes no parentheses, and the braces are not optional:
package main
import "fmt"
func main() {
age := 20
if age >= 18 {
fmt.Println("welcome in")
}
}
Writing if (age >= 18) compiles (the parens are just redundant), but
gofmt strips them. Omitting the braces, though, is a compile error. That
rule exists for a reason: in languages with optional braces, adding a second
line under a brace-less if silently changes the logic — the infamous bug
that caused Apple's "goto fail" security hole. Go removes the trap by
removing the choice.
if with an init statement
Like for, an if can run a short statement before its condition —
typically to create a value you only need for the check:
package main
import (
"fmt"
"strconv"
)
func main() {
if n, err := strconv.Atoi("42"); err == nil {
fmt.Println("parsed:", n)
}
// n and err don't exist out here.
}
n and err are scoped to the if (and its else, if there is one). This
is everywhere in real Go code, because so many functions return a value plus
an error — the init form lets you call, check, and move on without leaking
temporary names into the rest of the function.
else and else if
Chains work as you'd expect, with one grammar quirk: else must sit on the
same line as the closing brace before it. That's not style — a newline there
breaks compilation, just like the opening brace of func main().
package main
import "fmt"
func main() {
score := 74
if score >= 90 {
fmt.Println("excellent")
} else if score >= 50 {
fmt.Println("pass")
} else {
fmt.Println("try again")
}
}
Prefer early returns to deep nesting
Idiomatic Go handles the edge case first and returns, keeping the main path of a function flush against the left margin:
func greet(name string) string {
if name == "" {
return "Hello, stranger!"
}
return "Hello, " + name + "!"
}
Compare that with wrapping the happy path in else — one level deeper for
every check, until the code drifts off the right edge of the screen. Go
programmers call the flat version "line of sight": errors and edge cases exit
early on indented lines, and the successful path reads straight down. You'll
see this shape constantly once error handling arrives in force.
The exercise below is a classic early-return function: clamping a value into a range.
Practice
1. Clamp a Value
BeginnerImplement
clampso it forcesvinto the range[lo, hi]:func clamp(v, lo, hi int) int- If
vis less thanlo, returnlo. - If
vis greater thanhi, returnhi. - Otherwise
vis already in range — return it unchanged.
For example,
clamp(15, 0, 10)is10,clamp(-2, 0, 10)is0, andclamp(7, 0, 10)is7. Values exactly at the boundaries count as in range:clamp(0, 0, 10)is0.You may assume
lo <= hi. Try writing it with early returns instead of anif/else if/elsechain — both work, but the flat shape is the idiomatic one.package main import "fmt" // clamp forces v into the range [lo, hi]: values below lo become lo, // values above hi become hi, everything else passes through unchanged. func clamp(v, lo, hi int) int { // TODO: implement return 0 } func main() { fmt.Println(clamp(15, 0, 10)) }Sign in to write and run your solution in the browser.
Sign in for hints and the solution.
- If