5. If, else and switch in Go — A Book of Go

Louis Petrik
May 15, 2024

--

Source: the author

If and else

If-statements can have a short statement, e. g., for declaring the variable used:

if x := math.Pi; x < 3 {
fmt.Println("x is less than 3")
} else {
fmt.Println("x is greater than or equal to 3")
}

The variables used are only available in the scope of the if-statement.

Switch

The default is only run when no other case is matching:

var number int = 45

switch number {
case 42:
fmt.Println("is 42")
case 43:
fmt.Println("is 43")
default:
fmt.Println("is default")
}

Switch instead of if-else

Switch can be used to replace if-else in a cleaner way sometimes:

var number int = 45

switch {
case number == 50:
fmt.Println("Number is 50")
case number == 45:
fmt.Println("Number is 45")
case number == 40:
}

Next Chapter: For loops

--

--