Skip to content

Go Conditionals

Go handles decision-making through if/else and switch statements.

1. If/Else Statements

In Go, you don't need parentheses () around the condition, but curly braces {} are required.

1
2
3
4
5
if 7%2 == 0 {
    fmt.Println("7 is even")
} else {
    fmt.Println("7 is odd")
}

2. If with Initializer

A unique feature of Go is that if statements can start with a short statement to execute before the condition. Variables declared here are only available inside the if block.

1
2
3
4
5
6
7
if num := 9; num < 0 {
    fmt.Println(num, "is negative")
} else if num < 10 {
    fmt.Println(num, "has 1 digit")
} else {
    fmt.Println(num, "has multiple digits")
}

3. Switch Statements

switch is a cleaner way to write multiple if chains.

i := 2
switch i {
case 1:
    fmt.Println("one")
case 2:
    fmt.Println("two")
case 3:
    fmt.Println("three")
default:
    fmt.Println("other")
}

4. Switch without Expression

A switch without an expression is an alternate way to write long if/else if chains.

1
2
3
4
5
6
7
t := time.Now()
switch {
case t.Hour() < 12:
    fmt.Println("It's before noon")
default:
    fmt.Println("It's after noon")
}

Key Differences from other languages

  1. No implicit fallthrough: Go automatically breaks after each case. You don't need to write break.
  2. fallthrough keyword: If you want the execution to continue to the next case, you must explicitly use the fallthrough keyword.
  3. Multiple values: You can use commas to separate multiple values in a single case: case "Saturday", "Sunday":.