Initialization Statement in the if Statement
In the previous learning, the if
statement had only one parameter, the condition:
if condition {
code
}
The complete parameter also includes an initialization statement, which is an optional parameter in Go. It is typically used for the declaration and initialization of temporary variables, and the initialization statement is separated by a semicolon when used. The syntax is as follows:
if initialization statement; condition {
code
}
We have rewritten the program in the "if else" section. We moved the variable declaration to the if
statement as an initialization statement to shorten the code:
package main
import (
"fmt"
"time"
)
func main() {
if t := time.Now(); t.Weekday() == time.Saturday || t.Weekday() == time.Sunday {
fmt.Println("Today is:", t.Weekday(), "weekend, studying and recharging")
} else {
fmt.Println("Today is:", t.Weekday(), "also studying hard")
}
}
Run the program:
go run if_else.go
It can be seen that it runs correctly:
Today is: Monday also studying hard
Note: The scope of the variable declared in the initialization statement is only within the if
block.
I don't know if you Go gophers have noticed the formatting requirements of Go when learning if statements.
- In Go, the keywords
if
, else
, and else if
need to be on the same line as the right curly brace }
.
- The
else if
and else
keywords also need to be on the same line as the previous left curly brace, otherwise, the compiler will report a syntax error at compile time.
If we run the program after moving the else
statement to the next line, the compiler reports a syntax error.