- Go 教程
- Go —— 主页
- Go —— 概览
- Go —— 环境设置
- Go —— 程序结构
- Go —— 基本语法
- Go —— 数据类型
- Go —— 变量
- Go —— 常量
- Go —— 运算符
- Go —— 决策制定
- Go —— 循环
- Go —— 函数
- Go —— 范围规则
- Go —— 字符串
- Go —— 数组
- Go —— 指针
- Go —— 结构
- Go —— 切片
- Go —— 范围
- Go —— 映射
- Go —— 递归
- Go —— 类型转换
- Go —— 接口
- Go —— 错误处理
- Go 有用资源
- Go —— 问题与解答
- Go —— 快速指南
- Go —— 有用资源
- Go —— 讨论
Go —— 选择语句
Go 编程语言中 select 语句的语法如下 −
select {
case communication clause :
statement(s);
case communication clause :
statement(s);
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
以下规则适用于 select 语句 −
可以在一个 select 中有任何数量的 case 语句。每个 case 之后都跟要比较的值和一个冒号。
case 的 type 必须是通信通道操作。
当通道操作发生时,将执行 case 之后的语句。case 语句中不需要 break。
一个 select 语句可以有一个可选的 default case,它必须出现在 select 的末尾。default case 可用于在没有 case 为真时执行任务。default case 中不需要 break。
例子
package main
import "fmt"
func main() {
var c1, c2, c3 chan int
var i1, i2 int
select {
case i1 = <-c1:
fmt.Printf("received ", i1, " from c1\n")
case c2 <- i2:
fmt.Printf("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
fmt.Printf("received ", i3, " from c3\n")
} else {
fmt.Printf("c3 is closed\n")
}
default:
fmt.Printf("no communication\n")
}
}
在编译并执行以上代码后,它将产生以下结果 −
no communication
go_decision_making.htm
广告