Go 语言条件语句 8

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")
}
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值