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 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作