Go if & else 语句
最后修改时间 2024 年 4 月 11 日
在本文中,我们将展示如何在 Golang 中创建条件和分支。
Go if & else
if 语句指定了一个代码块的条件执行。如果表达式求值为 true,则执行该代码块。如果存在 else 语句且 if 语句的计算结果为 false,则执行 else 后的代码块。
可以有多个 if/else 语句。
Go if/else 示例
以下示例演示了使用 if/else 的代码块的条件执行。
main.go
package main
import "fmt"
func main() {
num := 4
if num > 0 {
fmt.Println("The number is positive")
}
}
在代码示例中,我们有一个简单的条件;如果 num 变量为正数,则将消息“The number is positive”打印到控制台。否则;不打印任何内容。
$ go run main.go The number is positive
由于值 4 是正数,因此打印了该消息。
我们使用 else 添加了另一个分支。
main.go
package main
import "fmt"
func main() {
num := -4
if num > 0 {
fmt.Println("The number is positive")
} else {
fmt.Println("The number is negative")
}
}
else 语句指定了在 if 条件失败时执行的代码块。
$ go run main.go The number is negative
接下来,我们使用 if else 添加附加分支。
main.go
package main
import (
"fmt"
"math/rand"
)
func main() {
num := -5 + rand.Intn(10)
if num > 0 {
fmt.Println("The number is positive")
} else if num == 0 {
fmt.Println("The number is zero")
} else {
fmt.Println("The number is negative")
}
}
我们生成 -5 到 4 之间的随机值。借助 if & else 语句,我们为所有三个选项打印了一条消息。
$ go run main.go The number is positive $ go run main.go The number is zero $ go run main.go The number is negative
我们运行了几次示例。
if 语句可以以在条件之前执行的简短语句开头。
main.go
package main
import (
"fmt"
"math/rand"
)
func main() {
if num := -5 + rand.Intn(10); num > 0 {
fmt.Println("value is positive")
} else if num == 0 {
fmt.Println("value is zero")
} else {
fmt.Println("value is negative")
}
}
前面的示例是用简短的 if 语句编写的。
检查 map 键是否存在
Go 为检查 map 中键是否存在提供了简短的写法。
main.go
package main
import "fmt"
func main() {
grades := map[string]int{
"Lucia": 2,
"Paul": 1,
"Merry": 3,
"Jane": 1,
}
if g, found := grades["Jane"]; found {
fmt.Println(g)
}
}
我们检查特定学生的成绩是否存在,如果存在,则打印其对应的值。
来源
The Go Programming Language Specification
在本文中,我们介绍了 Golang 中的 if/else 条件。