Conditions & Switches

Go conditional logic with if and switch statements.

if / else

Go does not require parentheses around conditions:

value := 10

if value > 10 {
    fmt.Println("big")
} else if value <= 10 && value != 0 {
    fmt.Println("medium")
} else {
    fmt.Println("small")
}

if with init statement

if err := doSomething(); err != nil {
    log.Fatal(err)
}
// err is not accessible here

switch

Go’s switch breaks automatically — no break needed:

command := "start"

switch command {
case "start":
    fmt.Println("starting")
case "stop", "quit":
    fmt.Println("stopping")
default:
    fmt.Println("unknown")
}

switch without condition

switch {
case value > 10:
    fmt.Println("big")
case value <= 10 && value != 0:
    fmt.Println("medium")
default:
    fmt.Println("small")
}

Type switch

func describe(v interface{}) {
    switch v.(type) {
    case int:
        fmt.Println("int")
    case string:
        fmt.Println("string")
    default:
        fmt.Println("unknown")
    }
}

Next: Collections & Loops