GoGo
BeginnerLesson 3 of 15

Conditions: if and switch – Go

Making decisions – without parentheses and without a ternary operator.

if needs no parentheses around the condition, but always curly braces around the block. The condition must be a bool. Go has no ternary operator (a ? b : c) – you use if/else instead.

package main

import "fmt"

func main() {
	punkte := 73
	if punkte >= 90 {
		fmt.Println("excellent")
	} else if punkte >= 70 {
		fmt.Println("good")
	} else {
		fmt.Println("needs improvement")
	}
}

An if may be preceded by a short statement. The variables declared there are only valid within the if/else block – this is the typical pattern for error checks:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	if n, err := strconv.Atoi("42"); err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("Number:", n+1) // Number: 43
	}
	// n and err are no longer visible here
}

switch stops automatically after a case (no break needed). Cases may have multiple values, and a switch without an expression replaces long if chains:

package main

import "fmt"

func main() {
	tag := "Sat"
	switch tag {
	case "Sat", "Sun":
		fmt.Println("Weekend")
	default:
		fmt.Println("Weekday")
	}

	punkte := 85
	switch {
	case punkte >= 90:
		fmt.Println("A")
	case punkte >= 80:
		fmt.Println("B") // B
	default:
		fmt.Println("C")
	}
}
TipThe comparison operators are ==, !=, <, >, <=, >=; you combine logically with &&, || and !. If you occasionally want to "fall through" into the next case, write fallthrough.