If Then Else
Examples
Filter
There is no ternary if in Go, so you’ll need to use a full if statement even for basic conditions.
package main
import "fmt"
func main() {
if 7%2 == 0 {
fmt.Println("7 is even")
} else {
fmt.Println("7 is odd")
}
if 8%4 == 0 {
fmt.Println("8 is divisible by 4")
}
if num := 9; num < 0 {
fmt.Println(num, "is negative")
} else if num < 10 {
fmt.Println(num, "has 1 digit")
} else {
fmt.Println(num, "has multiple digits")
}
}
Last Run
:
7 is odd
8 is divisible by 4
9 has 1 digit
a := 10
b := 20
if a < b {
println('$a < $b')
} else if a > b {
println('$a > $b')
} else {
println('$a == $b')
}
// if can be used as an expression:
num := 777
s := if num % 2 == 0 {
'even'
}
else {
'odd'
}
println(s) // "odd"
Last Run
:
10 < 20
odd