GoGoPrimer
< Back to module

Control flow

if / else

The `if` syntax looks like C or Java, with one difference: parentheses around the condition are forbidden (not just optional), and braces are mandatory even for a single statement.

age := 20
 
if age >= 18 {
fmt.Println("Majeur")
} else if age >= 13 {
fmt.Println("Adolescent")
} else {
fmt.Println("Enfant")
}

A handy feature: `if` accepts an initialization statement before the condition, separated by a semicolon. The variable declared this way only exists within the scope of the `if`/`else`, which avoids polluting the rest of the function.

if age := computeAge(birthDate); age >= 18 {
fmt.Println("Majeur")
}
// `age` n'existe plus ici, en dehors du bloc if

This `if value, err := doSomething(); err != nil { ... }` pattern comes up constantly in Go, because this is how the language handles errors (you'll see it again in the dedicated error-handling module).

Your turn

Write a `describeTemperature(celsius float64) string` function that returns "freezing" if <= 0, "cool" if <= 15, "pleasant" if <= 25, otherwise "hot".

func describeTemperature(celsius float64) string {
// à compléter
}