Master conditional logic in Go with if statements, boolean operators, error handling, and short if syntax
If statements are fundamental control flow structures that allow you to execute code conditionally based on boolean expressions. Go’s if statements are straightforward and powerful, with some unique features like short if declarations.
Go uses if statements extensively for error handling. The idiomatic pattern is to handle errors immediately and return early:
age := os.Args[1]// Atoi returns an int and an error valuen, err := strconv.Atoi(age)// Handle the error immediately and quitif err != nil { fmt.Println("ERROR:", err) return // Quit early}// Happy path continues here (err is nil)fmt.Printf("SUCCESS: Converted %q to %d.\n", age, n)
Go allows you to declare variables within the if statement itself. These variables are scoped to the if block:
if n, err := strconv.Atoi("42"); err == nil { // n and err are available here fmt.Println("There was no error, n is", n)}// n and err are NOT available here
This is particularly useful for error handling when you only need the variables within the if block:
if n, err := strconv.Atoi(input); err != nil { fmt.Println("ERROR:", err) return}// n is not available here
Variables declared in a short if statement are only accessible within that if block and its else branches:
if n, err := strconv.Atoi("42"); err == nil { fmt.Println("Success:", n) // n is available} else { fmt.Println("Error:", err) // n and err are available}// n and err are NOT available here
Be careful with shadowing:
n := 10 // Outer scopeif n, err := strconv.Atoi("42"); err == nil { fmt.Println(n) // This is the inner n (42), not the outer n (10)}fmt.Println(n) // This is the outer n (10)
if len(os.Args) != 2 { fmt.Println("Give me a year number") return}year, err := strconv.Atoi(os.Args[1])if err != nil { fmt.Printf("%q is not a valid year.\n", os.Args[1]) return}