09.4.3 通道作为函数参数传递

虽然 readCh.gowriteCh.go 没有使用这一功能,但 Go 允许您在把通道作为函数的参数时指定它的方向;那就是它是否用于读取或写入数据。通道有两种类型,无向通道和默认的双向通道。

查看下面两个函数代码:

func f1(c chan int, x int) {
    fmt.Println(x)
    c <- x
}

func f2(c chan<- int, x int){
    fmt.Println(x)
    c <- x
}

虽然两个函数实现了相同的功能,但它们的定义略有不同。f2() 函数的 chan 关键字右侧有个 <- 符号。这说明过 c 通道只能用于写数据。如果 Go 代码试图从一个只读通道(只发通道)读取数据的话,Go 编译器就会产生如下错误信息:

# command-line-arguments
a.go:19:11: invalid operation: range in (recevie from send-only type chan<- int)

同样,有下面的函数定义:

func f1(out chan int64, in chan int64) {
    fmt.Println(x)
    c <- x
}

func f2(out chan<- int64, in <-chan int64) {
    fmt.Println(x)
    c <- x
}

f2 定义含有名为 in 的只读通道和 out 的只写通道。如果您试图向函数的一个只读通道(只收通道)参数写数据和关闭它时,会得到如下错误信息:

# command-line-arguments
a.go:13:7: invalid operation: out <- i(send to receive-only type <-chan int)
a.go:15:7: invalid operation: close(out)(cannot close receive-only channel)

Last updated