dougaojue8185 2018-04-26 09:29
浏览 17
已采纳

选择语句通道示例

I'm new on golang and try to understand how the select statement work at https://www.tutorialspoint.com/go/go_select_statement.htm

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
")
      case c2 <- i2:
         fmt.Printf("sent ", i2, " to c2
")
      case i3, ok := (<-c3):  // same as: i3, ok := <-c3
         if ok {
            fmt.Printf("received ", i3, " from c3
")
         } else {
            fmt.Printf("c3 is closed
")
         }
      default:
         fmt.Printf("no communication
")
   }    
}   

There was no explanation about channels at this point. Now I have no idea, how to trigger another output as "no communication".

Can anyone give me an example for each case?

  • 写回答

1条回答 默认 最新

  • dongmie3526 2018-04-26 09:43
    关注

    The select statement chooses a case whose communication op would not block. If there are multiple cases whose comm. op would not block, one is chosen randomly.

    Since in the example all communication ops would block, and since a default is provided, that will be executed.

    To "trigger" another case, you have to make sure its comm. op does not block. In the example no one is sending or receiving anything from any of the channels that are used in the cases. Hell, they are not even initialized. And both sending to and receiving from a nil channel blocks forever (for details see How does a non initialized channel behave?). So you should do that: initialize a channel and send to / receive from it, the one whose case you want to trigger. For example:

    c1 = make(chan int, 1)
    c1 <- 1
    

    This snippet initializes the c1 channel with a buffer of 1, and sends a value on it. So in the select statement after this the communication operation i1 = <-c1 would not block, so this will be chosen, and the output will be:

    received  1  from c1
    

    Try it on the Go Playground. (Note: I changed all Printf() calls to Println().)

    Note that sending on / receiving from channels could happen concurrently, on other goroutines. I chose a buffered channel and the same goroutine for simplicity, and so that it behaves as you'd expect it even on the Go Playground.

    More about channels: What are golang channels used for?

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

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案