Go if else 语句
else 语句
使用 else
语句指定一个代码块,如果条件为 false
则执行。
语法
if condition {
// 如果 condition 为 true,则执行的代码
} else {
// 如果 condition 为 false,则执行的代码
}
使用 if else 语句
示例
在此示例中,时间 (20) 大于 18,因此 if
条件为 false
。因此,我们继续执行 else
条件,并在屏幕上打印“晚上好”。如果时间小于 18,程序将打印“白天好”。
package main
import ("fmt")
func main() {
time := 20
if (time < 18) {
fmt.Println("白天好。")
} else {
fmt.Println("晚上好。")
}
}
自己动手试一试 »
示例
在此示例中,温度为 14,因此 if
的条件为 false
,因此执行 else
语句内的代码行。
package main
import ("fmt")
func main() {
temperature := 14
if (temperature > 15) {
fmt.Println("外面很暖和。")
} else {
fmt.Println("外面很冷。")
}
}
自己动手试一试 »
else
语句中的括号应为 } else {
示例
将 else 括号放在不同行会引发错误。
package main
import ("fmt")
func main() {
temperature := 14
if (temperature > 15) {
fmt.Println("外面很暖和。")
} // 这会引发错误
else {
fmt.Println("外面很冷。")
}
}
结果
./prog.go:9:3: syntax error: unexpected else, expecting }