Go 语言中的条件语句用于根据某个条件执行不同的代码块。Go 语言提供了以下几种条件语句:
if 语句
if 语句用于根据某个条件执行不同的代码块。语法如下:
if condition {
// 代码块
}
其中,condition
是一个布尔表达式,如果为 true,就执行代码块。
例如:
x := 5
if x > 10 {
fmt.Println("x is greater than 10")
}
if-else 语句
if-else 语句用于根据某个条件执行不同的代码块。语法如下:
if condition {
// 代码块 1
} else {
// 代码块 2
}
其中,condition
是一个布尔表达式,如果为 true,就执行代码块 1,否则执行代码块 2。
例如:
x := 5
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than or equal to 10")
}
switch 语句
switch 语句用于根据某个值选择执行不同的代码块。语法如下:
switch value {
case value1:
// 代码块 1
case value2:
// 代码块 2
default:
// 代码块 3
}
其中,value
是一个值,value1
和 value2
是可能的值,default
是缺省值。
例如:
x := 5
switch x {
case 1:
fmt.Println("x is 1")
case 2, 3:
fmt.Println("x is 2 or 3")
default:
fmt.Println("x is other")
}
select 语句
select 语句用于选择执行多个代码块中的一个。语法如下:
select {
case expression1:
// 代码块 1
case expression2:
// 代码块 2
default:
// 代码块 3
}
其中,expression1
和 expression2
是可能的值,default
是缺省值。
例如:
ch := make(chan int)
select {
case x := <-ch:
fmt.Println("received", x)
default:
fmt.Println("no message received")
}