码迷,mamicode.com
首页 > 其他好文 > 详细

Go 只读/只写channel

时间:2015-06-02 00:08:40      阅读:921      评论:0      收藏:0      [点我收藏+]

标签:

Go中channel可以是只读、只写、同时可读写的。

//定义只读的channel

read_only := make (<-chan int)

 

//定义只写的channel

write_only := make (chan<- int)

 

//可同时读写

read_write := make (chan int)

 

定义只读和只写的channel意义不大,一般用于在参数传递中,见代码:

package main

import (
    "fmt"
    "time"
)

func main() {
    c := make(chan int)
    go send(c)
    go recv(c)
    time.Sleep(3 * time.Second)
}
//只能向chan里写数据
func send(c chan<- int) {
    for i := 0; i < 10; i++ {
        c <- i
    }
}
//只能取channel中的数据
func recv(c <-chan int) {
    for i := range c {
        fmt.Println(i)
    }
}

 

如果将上面send方法和recv方法中的参数对调:

func send(c <-chanint) {

func recv(c chan<- int) {

编译就会报错:

./channel.go:18: invalid operation: c <- i (send to receive-only type <-chan int)

./channel.go:24: invalid operation: range c (receive from send-only type chan<- int)

Go 只读/只写channel

标签:

原文地址:http://www.cnblogs.com/baiyuxiong/p/4545028.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!