if, else and the init statement
Go's if has no parentheses around the condition, and the braces are always required — even for one line. The condition must be a real bool: Go has no "truthy" values, so if count does not compile when count is an int.
An if can start with a short init statement before the condition, separated by a semicolon: if v := compute(); v > 10 { ... }. The variable exists only inside the if and its else branches. This is the idiomatic way to check an error without leaking err into the rest of the function.
package main
import (
"fmt"
"strconv"
)
func grade(score int) string {
if score >= 90 {
return "A"
} else if score >= 75 {
return "B"
} else {
return "C"
}
}
func main() {
fmt.Println(grade(95), grade(80), grade(40))
for _, text := range []string{"42", "forty"} {
if n, err := strconv.Atoi(text); err != nil {
fmt.Println("not a number:", text)
} else {
fmt.Println("doubled:", n*2)
}
// n and err do not exist here
}
}A B C
doubled: 84
not a number: fortyAdd a "A+" grade for scores of 98 and above. Where must that branch go in the chain, and why?
if err != nil { return err }. Deeply nested else blocks are a code-review smell. Linters even flag an else after a branch that ends in return.non-boolean condition in if statement
package main
import "fmt"
func main() {
count := 3
if count {
fmt.Println("have items")
}
}# command-line-arguments
./main.go:7:5: non-boolean condition in if statementIn C, JavaScript or Python a non-zero number counts as true. Go deliberately has no truthiness: a condition must have type bool, so the intent is always written out.
Write the comparison you mean.
package main
import "fmt"
func main() {
count := 3
if count > 0 {
fmt.Println("have items")
}
}There is no ternary operator
package main
import "fmt"
func main() {
age := 20
label := age >= 18 ? "adult" : "minor"
fmt.Println(label)
}# command-line-arguments
./main.go:7:21: invalid character U+003F '?'
./main.go:7:23: syntax error: unexpected literal "adult" at end of statementGo left out ? : on purpose — the designers found nested ternaries hard to read. ? is not even a valid character in Go source outside strings.
Declare the variable, then set it with an if.
package main
import "fmt"
func main() {
age := 20
label := "minor"
if age >= 18 {
label = "adult"
}
fmt.Println(label)
}