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语言学习(五):通道的用法

返回前面的内容

相关阅读 >>

Golang lua怎么用

手撸Golang 基本数据结构与算法 归并排序

详解Golang如何对excel进行处理

Golang判断字符是不是字母

Go关于tpl文件无法读取域中数据{{$.name}}

jack liu's Golang personal summary notes

专访Go语言布道师dave cheney:Go语言这十年,只能用“成功”一词总结

聊聊Go-ddd-sample

Golang编译为什么快

Go 在证券行情系统中的应用

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




打赏

取消

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

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

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

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

评论

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