If/Else
Conditional branching with if, else if, and else - including the idiomatic init-statement form used for error checks.
Go's if statement runs code when a condition is true. Conditions do not need parentheses, and an if can begin with a short setup statement before the condition is checked.
A simple if/else if/else chain. Each condition must be a boolean, meaning it must evaluate to true or false.
package main
import "fmt"
func main() {
x := 7
if x > 10 {
fmt.Println("big")
} else if x > 4 {
fmt.Println("medium")
} else {
fmt.Println("small")
}
// medium
}The setup statement runs once before Go checks the condition. A variable declared there is available only inside that if and its else branches.
package main
import (
"fmt"
"strconv"
)
func main() {
if n, err := strconv.Atoi("42"); err == nil {
fmt.Println("parsed:", n)
} else {
fmt.Println("error:", err)
}
// parsed: 42
// n and err are not accessible here
}This form is often used to check an operation's error right away. The error variable exists only inside the if and else branches.
package main
import (
"fmt"
"os"
)
func main() {
if f, err := os.Open("data.txt"); err != nil {
fmt.Println("cannot open:", err)
} else {
defer f.Close()
fmt.Println("opened:", f.Name())
}
}In production
When a function returns an error, check it before using the other result. A common check is if err != nil { return err }, which stops the current function and passes the error back to its caller.