go语言学习(五):通道的用法


当前第2页 返回上一页

我们把接收操作赋值给2个参数,第二个参数就能判断通道是否已经关闭。比如用for循环接收通道中的元素,代码如下:

for {
    elem, ok := <-ch1
    if !ok {
      fmt.Printf("Receiver: close channel\n")
      break
    }
    fmt.Printf("Receiver: received an element:%v\n", elem)
  }

在我们开发过程中,有时候为了在方法参数中定义一个通道来收发数据,会定义一个单向通道,如下面代码,第一个通道只能发,第二个通道只能收

var sendChan = make(chan<- int, 1)
var receiveChan1 = make(<- chan int, 1)

还可以定义返回值是单向通道的函数,如下:

func getIntChan() <- chan int{}
func getIntChan1()  chan <- int{}

go语言为通道提供了select语句配合使用,类似于java中的switch,也有一个默认的分支,示例如下:

func main() {
  // 准备好几个通道。
  intChannels := [3]chan int{
    make(chan int, 1),
    make(chan int, 1),
    make(chan int, 1),
  }
  // 随机选择一个通道,并向它发送元素值。
  index := rand.Intn(3)
  fmt.Printf("The index: %d\n", index)
  intChannels[index] <- index
  // 哪一个通道中有可取的元素值,哪个对应的分支就会被执行。
  select {
  case <-intChannels[0]:
    fmt.Println("The first candidate case is selected.")
  case <-intChannels[1]:
    fmt.Println("The second candidate case is selected.")
  case elem := <-intChannels[2]:
    fmt.Printf("The third candidate case is selected, the element is %d.\n", elem)
  default:
    fmt.Println("No candidate case is selected!")
  }
}

注意:在for循环中使用select,如果要屏蔽某个case分支,可以将通道赋值为nil


本文来自:51CTO博客

感谢作者:mb5fed72b60246f

查看原文:go语言学习(五):通道的用法

返回前面的内容

相关阅读 >>

Go 语言入门系列:数组的使用

聊聊dubbo-Go-proxy的parammapper

[Go] Golang 中main包下入口文件调用其它Go文件函数出现undefined

Go入门-1 变量

手撸Golang Go与微服务 saga模式之2

记一次因为共享变量的犯错误

Golang如何复用http.request.body

Go语言学习9-结构体类型

10 Golang map的正确使用姿势

手撸Golang spring ioc/aop 之2

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...