Beginner Fundamentals
Conditionals
Conditionals let your program choose what to do based on a boolean expression. Go uses if and else.
Basic if
No parentheses around the condition, but braces are required.
age := 20
if age >= 18 {
fmt.Println("Adult")
}
if / else
score := 70
if score >= 60 {
fmt.Println("Pass")
} else {
fmt.Println("Fail")
}
else if
grade := 85
if grade >= 90 {
fmt.Println("A")
} else if grade >= 80 {
fmt.Println("B")
} else {
fmt.Println("C or lower")
}
if with a short statement
You can run a statement before the condition. Variables declared there are only visible inside the if/else.
if n := 10; n%2 == 0 {
fmt.Println(n, "is even")
} else {
fmt.Println(n, "is odd")
}
This pattern keeps temporary variables scoped tightly to where they are used.