if else
在本教程中,您将学习如何编写用于在 Golang 中执行不同操作的决策条件语句。
像大多数编程语言一样,Golang 从 C 系列语言中借用了几种控制流语法。在 Golang 中,我们有以下条件语句:
- if语句 - 如果一个条件为真,则执行一些代码
- if...else语句 - 如果条件为真,则执行一些代码,如果条件为假,则执行另一个代码
- if…else if....else语句 - 对两个以上的条件执行不同的代码
- switch...case语句 - 选择要执行的众多代码块之一
我们将在接下来的部分中探讨这些陈述中的每一个。
if 语句
if语句用于仅在指定条件的计算结果为 true 时才执行代码块。
if condition {
// code to be executed if condition is true
}
下面的示例将输出“日本”,如果X为真:
package main
import (
"fmt"
)
func main() {
var s = "Japan"
x := true
if x {
fmt.Println(s)
}
}
If…else语句
语句允许您在指定的条件计算结果为 true 时执行一个代码块,如果计算结果为 false,则执行另一个代码块。
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
下面的示例将输出“日本”,如果X为100:
package main
import (
"fmt"
)
func main() {
x := 100
if x == 100 {
fmt.Println("Japan")
} else {
fmt.Println("Canada")
}
}
if...else if...else语句
if … else if … else语句允许组合多个else if。
if condition-1 {
// code to be executed if condition-1 is true
} else if condition-2 {
// code to be executed if condition-2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
下面的示例将输出“日本”,如果X为100:
package main
import (
"fmt"
)
func main() {
x := 100
if x == 50 {
fmt.Println("Germany")
} else if x == 100 {
fmt.Println("Japan")
} else {
fmt.Println("Canada")
}
}
if语句初始化
If语句支持复合语法,其中测试的表达式前面有一个初始化语句。
if var declaration; condition {
// code to be executed if condition is true
}
如果X为100,下面的示例将输出“德国”:
package main
import (
"fmt"
)
func main() {
if x := 100; x == 100 {
fmt.Println("Germany")
}
}