TExcelTAD
Home › Go › Go If..Else

Go If..Else

Conditional statements let your program choose between different paths. Go's if looks like other C-family languages, with two differences: no parentheses around the condition, and the braces are always required, even for a single statement.

if

go · try it yourself
package main

import "fmt"

func main() {
	temperature := 31

	if temperature > 30 {
		fmt.Println("It's hot — drink some water.")
	}
	fmt.Println("Forecast done.")
}
It's hot — drink some water.
Forecast done.

if … else

else runs when the condition is false. It must be on the same line as the closing } of the if block — otherwise automatic semicolon insertion breaks the statement.

go · try it yourself
package main

import "fmt"

func main() {
	balance := 40
	price := 55

	if balance >= price {
		fmt.Println("Purchase approved")
	} else {
		fmt.Println("Insufficient funds, missing", price-balance)
	}
}
Insufficient funds, missing 15

else if chains

Use else if to test several conditions in order. The first one that is true wins; the rest are skipped.

go · try it yourself
package main

import "fmt"

func grade(score int) string {
	if score >= 90 {
		return "A"
	} else if score >= 80 {
		return "B"
	} else if score >= 70 {
		return "C"
	} else {
		return "F"
	}
}

func main() {
	for _, s := range []int{95, 83, 71, 40} {
		fmt.Println(s, "->", grade(s))
	}
}
95 -> A
83 -> B
71 -> C
40 -> F

if with a short statement

An if can begin with a short statement, separated from the condition by a semicolon. Variables declared there are only visible inside the if and its else branches. This is extremely common with functions that return an error.

go · try it yourself
package main

import (
	"fmt"
	"strconv"
)

func main() {
	if n, err := strconv.Atoi("42"); err != nil {
		fmt.Println("not a number:", err)
	} else {
		fmt.Println("parsed", n, "doubled is", n*2)
	}

	if n, err := strconv.Atoi("forty"); err != nil {
		fmt.Println("not a number:", err)
	} else {
		fmt.Println("parsed", n)
	}
	// n and err do not exist here
}
parsed 42 doubled is 84
not a number: strconv.Atoi: parsing "forty": invalid syntax

Nested if

You can put an if inside another. But deep nesting gets hard to read quickly — Go programmers prefer early returns ("guard clauses") that handle the unusual case first and keep the main path un-indented.

go · try it yourself
package main

import "fmt"

// Nested version
func canRentNested(age int, hasLicense bool) string {
	if age >= 21 {
		if hasLicense {
			return "yes"
		} else {
			return "no: license required"
		}
	} else {
		return "no: too young"
	}
}

// Early-return version: same logic, flatter
func canRent(age int, hasLicense bool) string {
	if age < 21 {
		return "no: too young"
	}
	if !hasLicense {
		return "no: license required"
	}
	return "yes"
}

func main() {
	fmt.Println(canRentNested(25, true), "|", canRent(25, true))
	fmt.Println(canRentNested(25, false), "|", canRent(25, false))
	fmt.Println(canRentNested(19, true), "|", canRent(19, true))
}
yes | yes
no: license required | no: license required
no: too young | no: too young

Note: Go has no ternary operator (cond ? a : b). Use a regular if/else, or assign a default first and override it in an if.

Rule Example
No parentheses needed if x > 0 {
Braces always required if ok { return }
else on the same line as } } else {
Optional init statement if v, ok := m[k]; ok {

Common mistakes

A few errors trip up almost everyone coming from other languages:

  • Putting else on its own line. The closing } followed by a newline ends the statement, so else on the next line is a syntax error. Always write } else {.
  • Using = instead of ==. In Go, assignment is a statement, not an expression, so if x = 5 { does not compile — the compiler catches the typo for you.
  • Shadowing a variable in the init statement. if err := f(); err != nil { ... } creates a new err that disappears after the if. If you need the value later, declare it before the if.
  • Writing if found == true. It works, but if found is shorter and idiomatic; likewise if !found instead of if found == false.

Test yourself

Which if is valid Go?

  1. if (x > 5) fmt.Println(x)
  2. if x > 5 { fmt.Println(x) }
  3. if x > 5: fmt.Println(x)
  4. if x > 5 then fmt.Println(x)

Where is a variable declared in if v := f(); v > 0 { ... } visible?

  1. In the whole function
  2. Only in the if, else if and else blocks
  3. Only in the if block
  4. In the whole package

Does Go have a ternary operator like a > b ? a : b?

  1. Yes
  2. No
  3. Only for numbers
  4. Only in constants