if else statement
What should we do if we want to output something else when the condition in the if statement is not met? In this case, we can use the if else
statement. If the condition in the if statement is true, it runs the code block in the if statement; otherwise, it runs the code block in the else statement.
The format of the if else
statement is similar to the if statement:
if condition {
code
} else {
code
}
Let's look at an example. The following program will output whether today is a weekday or a weekend:
package main
import (
"fmt"
"time"
)
func main() {
// Get the current time
t := time.Now()
// Check whether it is Saturday or Sunday
if t.Weekday() == time.Saturday || t.Weekday() == time.Sunday {
fmt.Println("Today is:", t.Weekday(), "weekend")
} else {
fmt.Println("Today is:", t.Weekday(), "weekday")
}
}
The result is as follows:
Today is: Monday weekday
We use the time
package from the standard library to get the current time. Then, by comparing it with Saturday and Sunday, if it is a weekend, the code block in the if statement is executed; otherwise, the code block in the else statement is executed.