这是Golang系列教程 的第8个教程
文章目录
if 是一个条件语句,if 语句的语法是
if condition {
}
如果 condition
为真,{
和 }
之间的代码行被执行。
和其他 C 之类的语言不一样,{ }
是强制性的,即使在 {}
之间只有一条语句。
if 语句也有可选的 else if
和 else
部分
if condition {
} else if condition {
} else {
}
可以有任意数量的 else if
。从上到下评估条件是否为真实性。 任何 if
或 else if
被评估为真,就执行相应的代码块。如果条件都不为真,则执行 else
块。
我们来写一个简单的程序,找出一个数字是偶数还是奇数
package main
import (
"fmt"
)
func main() {
num := 10
if num % 2 == 0 { //checks if number is even
fmt.Println("the number is even")
} else {
fmt.Println("the number is odd")
}
}
语句 if num % 2 == 0
检查数字对 2 取余是否为0,如果是,则 the number is even
被打印,否则,打印 the number is odd
。上面的程序打印 the number is even
。
if
语句还有一个变种,它包含一个可选的 statement
组件,它在条件评估之前被执行。它的语法是
if statement; condition {
}
我们使用上面的语法重写发现数字是奇数还是偶数的程序
package main
import (
"fmt"
)
func main() {
if num := 10; num % 2 == 0 { //checks if number is even
fmt.Println(num,"is even")
} else {
fmt.Println(num,"is odd")
}
}
在上面的程序中 num
在 if
语句中被初始化。需要注意的是 num
仅可以在 if
和 else
语句中被访问,即 num
的作用域被限定在 if
else
块中。如果我们试图在 if
或 else
外访问 num
。编译器将抱怨。
我们使用 else if
再写一个程序
package main
import (
"fmt"
)
func main() {
num := 99
if num <= 50 {
fmt.Println("number is less than or equal to 50")
} else if num >= 51 && num <= 100 {
fmt.Println("number is between 51 and 100")
} else {
fmt.Println("number is greater than 100")
}
}
在上面的程序中,else if num >= 51 && num <= 100
为真,因此程序输出 number is between 51 and 100
。
疑难杂症
else
语句必须和 if
语句的结束符 }
在同一行的后面,否则编译器将抛异常
我们写个程序来理解这一点
package main
import (
"fmt"
)
func main() {
num := 10
if num % 2 == 0 { //checks if number is even
fmt.Println("the number is even")
}
else {
fmt.Println("the number is odd")
}
}
在上面的程序中,else
语句并不是在 if 语句的结束符 }
同一行的后面。而是另起一行,这在 Go 中是不被允许的,如果运行这个程序,编译器将打印错误
main.go:12:5: syntax error: unexpected else, expecting }
出现这个的原因是由于 Go 会自动添加分号,你可以阅读 分号插入规则。
在规则中,指定如果它是一行的结束标记,在 }
后,将插入一个分号。所以分号被自动插入到 if 语句的结尾 }
。
所以我们的程序实际上是
if num%2 == 0 {
fmt.Println("the number is even")
}; //semicolon inserted by Go
else {
fmt.Println("the number is odd")
}
由于 if{...} else {...}
是一个语句,它中间不应该出现分号。因此在结束符 }
后的同一行添加一个 else
是必要的。
下面是我重写后的程序
package main
import (
"fmt"
)
func main() {
num := 10
if num%2 == 0 { //checks if number is even
fmt.Println("the number is even")
} else {
fmt.Println("the number is odd")
}
}
** 下一教程 - 循环 **