只有在满足某个条件时,才导致代码块(一个或多个由花括号{}包围的语句)被执行的语句。
if 1 < 2 { fmt.Println("It's true!")}
复制代码
计算表达式,如果结果为 true,则执行条件块体中的代码。如果为 false,则跳过条件块。
if true { fmt.Println("this line is printed")}if false { fmt.Println("this line is not printed")}
复制代码
与大多数其他语言一样, Go 也支持条件语句中的多个分支。这些语句采用 if...else if...else 的形式。
if grade == 100 { fmt.Println("perfect") } else if grade >= 60 { fmt.Println("passed") } else { fmt.Println("failed") }
复制代码
条件语句依赖于布尔表达式(计算结果为 true 或 false)来决定是否应执行它们所包含的代码。
package main
import ( "fmt")
func main() { if 1 == 1 { fmt.Println("1==1") } if 1 >= 2 { fmt.Println("1>=2") } if 1 >= 0 { fmt.Println("1>=0") } if 1 < 2 { fmt.Println("1<2") } if 1 < 0 { fmt.Println("1<0") }}
// console1==11>=01<2
Program exited.
复制代码
当你仅在条件为假时才需要执行代码时,可以使用“!”布尔求反运算符,它允许你获取一个真值并使其为假,或者获取一个假值并使其为真。
package main
import ( "fmt")
func main() { if !true { fmt.Println("this is false") } else { fmt.Print("this is true") }}
// consolethis is trueProgram exited.
复制代码
如果只希望在两个条件都为真时运行一些代码,可以使用 &&(“与”)运算符。如果你想让它在两个条件之一为真时运行,你可以使用 || (“或”)运算符。
package main
import ( "fmt")
func main() { if true && false { fmt.Print("true && false") } if true || false { fmt.Print("true || false") }}
// consoletrue || falseProgram exited.
复制代码
补充
Golang 不要求 if 语句的条件用圆括号括起来。go fmt 工具会删除你添加的任何圆括号,除非圆括号是用来设置运算顺序的。
评论