Go if else Statement
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Using The if else Statement
Example
In this example, time (20) is greater than 18, so the
if condition is false.
Because of this, we move on to the else
condition and print to the screen "Good evening". If the time was less than
18, the program would print "Good day":
import "fmt"
func main() {
time := 20
if (time < 18) {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}
Example
In this example, the temperature is 14 so the condition for if is false so the
code line inside the else statement is executed:
import "fmt"
func main() {
temperature := 14
if (temperature > 15) {
fmt.Println("It is warm out there")
} else {
fmt.Println("It is cold out there")
}
}
The brackets in the else statement should be like } else {:
Example
Having the else brackets in a different line will raise an error:
import "fmt"
func main() {
temperature := 14
if (temperature > 15) {
fmt.Println("It is warm out there.")
} // this raises an error
else {
fmt.Println("It is cold out there.")
}
}
Result:
./prog.go:9:3: syntax error: unexpected else, expecting }