duanaixuan7385 2019-03-04 06:55
浏览 21
已采纳

为什么选择GoLang中的语句

Am learning Go and here in this example, i can see that select statement lets a goroutine wait on multiple communication operations

Do we really need a select statement ? My below does the same without select statement

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()
}

Without the select statment, i was able to wait for both the channels to get their values... Why we would need Select statement ? Can someone educate me please ?

  • 写回答

1条回答 默认 最新

  • douliangpo0128 2019-03-04 07:13
    关注

    Do we really need a select statement ?

    Yes. No user code can select exactly one of several possible channel operations if several are able to execute or none (default) if no case is ready.

    (Your code does something completely different.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效