The else Statement
- Use the else statement to specify a block of code to be executed if the condition is false.
Syntax:
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example1:
package main
import "fmt"
func main() {
if t := 20; t < 18 {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}
import "fmt"
func main() {
if t := 20; t < 18 {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}
Example2:
package main
import "fmt"
func main() {
temperature := 14
if temperature > 15 {
fmt.Println("It is warm out there")
} else {
fmt.Println("It is cold out there")
}
Example3:
- Placing the else keyword on a new line, separated from the closing brace of the if block, causes a compile‑time error. In Go, the else must begin on the same line as the preceding } (with at least one space between them).
package main
import "fmt"
func main() {
temperature := 14
if temperature > 15 {
fmt.Println("It is warm out there.")
} else { // ← note: “else” sits on the same line as the closing brace
fmt.Println("It is cold out there.")
}
}