Conditionals (if-else & switch)

🐹 Go Language Lesson 4 Beginner

Conditionals control program branch paths using boolean checks. Go provides an initializer syntax for conditionals and prevents switch statement fall-through bugs by default.

1 If Initializer Statements & Switch fallthrough rules

Go supports two key conditional enhancements:

  • If Statements with Initializers: You can execute a short statement before the condition is evaluated. Variables declared in this statement are only visible inside the scope of the if-else block: `if val := getVal(); val > 10 {}`.
  • No Automatic Switch Fall-through: Switch statements evaluate only the matching case and exit automatically, eliminating the need for `break` statements. If you explicitly want fall-through behavior, use the **`fallthrough`** keyword.
2 Conditionals Code

Let's run a program executing initializer conditionals and switch structures:

Go — Conditional Structures ▶ Run Code
package main

import "fmt"

func main() {
    // If with initializer (score is only visible within the if block)
    if score := 85; score >= 90 {
        fmt.Println("Grade: A")
    } else if score >= 80 {
        fmt.Println("Grade: B")
    } else {
        fmt.Println("Grade: F")
    }

    // Switch case with no break required
    dayNum := 2
    switch dayNum {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday") // Execution exits here automatically
    case 3:
        fmt.Println("Wednesday")
    default:
        fmt.Println("Invalid Day")
    }
}
3 Code Challenge
Challenge: Write a switch statement that evaluates an integer score (1-5). Use the `fallthrough` keyword to print both the matching rating and the rating below it to verify the fall-through behavior.