Golang 实现选择语句
Golang的选择语句与switch语句类似,switch语句根据情况选择输出,但在这里,根据通道中发生的通信来选择输出。
语法
func make ([] type, size, capacity)
在Go语言中, make 函数用于创建数组/映射,它接受要创建的变量类型、大小和容量作为参数。
time.Sleep()
这个函数属于time包。这里,sleep这个词描述了函数的含义,它表示将会阻塞goroutine的执行,阻塞的时间是一个特定的时间量。
time.Second()
这个函数是time包的一部分,主要用于表示持续的秒数。
步骤
- 步骤1 - 在程序中导入所需的包
-
步骤2 - 创建一个主函数,并在主函数中使用内置函数创建两个通道
-
步骤3 - 使用go协程将数据发送到通道,并使用sleep在选择语句退出之前接收消息
-
步骤4 - 使用选择语句从任何一个通道接收到输出时将其打印到控制台上
-
步骤5 - 使用fmt包中的Println函数执行打印语句
示例1
在这个示例中,我们将通过创建两个通道并使用go协程将数据发送到通道来实现选择语句。选择语句将用于从通道接收数据,并将首先接收到的数据打印到控制台上。
package main
import (
"fmt"
"time"
)
func main() {
channel1 := make(chan string)
channel2 := make(chan string)
go func() {
time.Sleep(2 * time.Second)
channel1 <- "good"
}()
go func() {
time.Sleep(3 * time.Second)
channel2 <- "morning"
}()
select {
case msg1 := <-channel1:
fmt.Println(msg1)
case msg2 := <-channel2:
fmt.Println(msg2)
}
}
输出
good
示例2
在这个示例中,将创建两个通道。Go协程将用于向通道发送数据,然后使用select语句从通道获取输出作为接收到的数据,但如果没有收到消息,也将使用默认值。
package main
import (
"fmt"
"time"
)
func main() {
channel1 := make(chan string)
channel2 := make(chan string)
go func() {
time.Sleep(2 * time.Second)
channel1 <- "good"
}()
go func() {
time.Sleep(3 * time.Second)
channel2 <- "morning"
}()
select {
case msg1 := <-channel1:
fmt.Println(msg1)
case msg2 := <-channel2:
fmt.Println(msg2)
default:
fmt.Println("No messages received")
}
}
输出
No messages received
结论
我们编写并执行了使用两个示例实现select语句的程序。在这两个示例中,我们使用了类似的通道,但唯一的区别是在第二个示例中,如果没有从通道接收到消息,就会使用默认情况。