[TOC]
golang 函数返回chan类型
在阅读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()
对于代码中的
经查阅资料,得知上面返回的是一个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
创建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()
创建func A()
# command-line-arguments
.test2.go:29:7: invalid operation: r
同理, 如果返回类型为 chan
如何声明和初始化单向channel
var ch1 chan
var ch2
ch3 := make(chan
ch4 := make(