gpt4 book ai didi

go - 为什么在 Go 语言中使用 select 语句

转载 作者:IT王子 更新时间:2023-10-29 01:49:53 25 4
gpt4 key购买 nike

正在学习 Go 并在 this example 中,我可以看到 select 语句让 goroutine 等待多个通信操作

我们真的需要一个select语句吗?我的下面在没有 select 语句的情况下执行相同的操作

func runForChannel1(channel1 chan string) {
time.Sleep(1 * time.Second)
channel1 <- "Hi Arun ... I am Channel-1"
}

func runForChannel2(channel2 chan string) {
time.Sleep(2 * time.Second)
channel2 <- "Hi Arun ... I am Channel-2"
}

func testSelect() {
channel1 := make(chan string)
channel2 := make(chan string)

go runForChannel1(channel1)
go runForChannel2(channel2)

chval1, chval2 := <-channel1, <-channel2
fmt.Println(chval1, chval2)

}

func main() {
testSelect()
}

如果没有 select 语句,我可以等待两个 channel 都获得它们的值...为什么我们需要 Select 语句?有人可以教我吗?

最佳答案

Do we really need a select statement ?

是的。没有用户代码可以选择几个可能的 channel 操作中的一个(如果有多个 channel 操作能够执行)或者没有(默认)如果没有案例准备好。

(您的代码做了完全不同的事情。)

关于go - 为什么在 Go 语言中使用 select 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54978013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com