Go Tutorial · Control Flow · Lesson 10 of 30
Go If Else
Conditions, if with a short statement, and error checks.
if, else if, else
No parentheses around the condition; braces are required:
package main
import "fmt"
func main() {
temp := 31
if temp > 30 {
fmt.Println("Hot")
} else if temp > 20 {
fmt.Println("Warm")
} else {
fmt.Println("Cold")
}
}
Output
Hot
Run this on your computer — see “Get Started” for setup.
if with a short statement
if can start with a statement whose variables are scoped to the if/else blocks. You'll see this everywhere for error handling:
package main
import (
"fmt"
"strconv"
)
func main() {
if n, err := strconv.Atoi("42"); err == nil {
fmt.Println("parsed", n)
}
if _, err := strconv.Atoi("forty-two"); err != nil {
fmt.Println("error:", err)
}
}
Output
parsed 42 error: strconv.Atoi: parsing "forty-two": invalid syntax
Run this on your computer — see “Get Started” for setup.
Test yourself
Are parentheses required around an if condition in Go?
YesNo
Show answer
Answer: No