当前位置 博文首页 > golang 函数返回chan类型的操作

    golang 函数返回chan类型的操作

    作者:CodeMechine 时间:2021-05-31 17:59

    在阅读kafka的golang 客户端代码sarama-cluster时,遇到了如下一段代码:

    // Messages returns the read channel for the messages that are returned by
    // the broker.
    //
    // This channel will only return if Config.Group.Mode option is set to
    // ConsumerModeMultiplex (default).
    func (c *Consumer) Messages() <-chan *sarama.ConsumerMessage { return c.messages }
    

    对于代码中的<-chan *sarama.ConsumerMessage产生了疑问,这个是什么意思呢?

    经查阅资料,得知上面返回的是一个read-only类型的channel,即只读的管道。

    验证:

    package main
    import (
        "fmt"
    )
    type C struct {
        Name string
    }
    type D struct {
        Id chan C
    }
    func (d *D)A() chan C {
        return d.Id
    }
    func main() {
        c := C{
            Name: "test",
        }
        ch := make(chan C, 10)
        ch <- c
        d := D{
            Id: ch,
        }
        r := d.A()
        r <- c
        for i:=0;i<=len(r);i++ {
            fmt.Printf("%v", <-r)
        }
    }
    

    创建func A() chan C {}, 在调用A()后,返回值r为channel, 其仍可以写入对象c,输出结果为:

    {test}{test}
    Process finished with exit code 0
    package main
    import (
        "fmt"
    )
    type C struct {
        Name string
    }
    type D struct {
        Id chan C
    }
    func (d *D)A() <-chan C {
        return d.Id
    }
    func main() {
        c := C{
            Name: "test",
        }
        ch := make(chan C, 10)
        ch <- c
        d := D{
            Id: ch,
        }
        r := d.A()
        r <- c
        for i:=0;i<=len(r);i++ {
            fmt.Printf("%v", <-r)
        }
    }
    

    创建func A() <-chan C {}, 在调用A()后,返回值r为channel, 但无法向r中写入对象c,会报语法错误,输出结果为:

    # command-line-arguments
    .\test2.go:29:7: invalid operation: r <- c (send to receive-only type <-chan C)
    Compilation finished with exit code 2
    

    同理, 如果返回类型为 chan<- type,则返回的是write-only类型的channel,即只能写不能读。

    如何声明和初始化单向channel

    var ch1 chan<- int  // 声明ch1,只用于写int数据
    var ch2 <-chan int  // 声明ch2,只用于读int数据
    ch3 := make(chan<- int, 10)  // 初始化一个只写的channel
    ch4 := make(<-chan int, 10)  // 初始化一个只读的chaannel

    补充:golang chan<- 和 <-chan,作为函数参数时

    开始时看到这个实在没明白怎么回事

    测试了下才知道原来

    <-chan int 像这样的只能接收值

    chan<- int 像这样的只能发送值

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持站长博客。如有错误或未考虑完全的地方,望不吝赐教。

    js