Notessh2a

Conditions

If-else Statement

Executes a block of code when a condition is true.

if condition {
    // code runs if condition is true
} else if anotherCondition {
    // code runs if it gets here and anotherCondition is true
} else {
    // code runs if none of the above are true
}
  • Go lets you declare a variable that only exists in the if and else blocks:

    s := "Hello"
    
    if n := len(s); n == 1 {
    	fmt.Println("n is:", n)
    } else if n >= 2 {
    	fmt.Println("n is:", n)
    } else {
    	fmt.Println("Empty string", n)
    }
    
    // n is: 5
    
    fmt.Println("n is:", n) // <-- compiler: undefined: n

Switch Statement

Executes the block for the matching case.

switch expression {
case value1:
    // code runs if expression == value1
case value2:
    // code runs if expression == value2
case value3, value4:
    // code runs if expression == value3 or value4
default:
    // code runs if expression does not match any case
}

Go auto break after each case implicitly, but the keyword can still be used.

  • Using the fallthrough keyword overrides the implicit break behavior and continues execution into the next case:

    a := 2
    
    switch a {
    case 1:
        fmt.Println("One")
    case 2:
        fmt.Println("Two")
        fallthrough
    case 3:
        fmt.Println("Three")
    case 4:
        fmt.Println("Four")
    default:
        fmt.Println("None of above")
    }
    
    // Two
    // Three
  • You can also declare a variable for case matching that only exists within the switch block:

    s := "hi"
    
    switch n := len(s); n {
    case 1:
    	fmt.Println("n is:", n)
    case 2:
    	fmt.Println("n is:", n)
    default:
    	fmt.Println("None of above", n)
    }
    
    // n is: 2
    
    fmt.Println("n is:", n) // <-- compiler: undefined: n
  • Omitting the expression makes the switch statement act like an if-else statement:

    a := 3
    
    switch {
    case a == 1:
        fmt.Println("One")
    case a == 2:
        fmt.Println("Two")
    case a == 3 || a == 4:
        fmt.Println("Three or Four")
    default:
        fmt.Println("None of above")
    }
    
    // Three or Four

On this page