在 Go 中创建单向通道有什么意义

What's the point of creating one-way channels in Go

在 Go 中可以创建单向通道。如果想要限制给定通道上可用的一组操作,这是一个非常方便的功能。然而,据我所知,此功能仅对函数的参数和变量的类型规范有用,而通过 make 创建单向通道对我来说看起来很奇怪。我读过这个 question,但它不是关于在 Go 中创建只读(或写)通道,而是关于一般用法。所以,我的问题是关于下一个代码的用例:

writeOnly := make(chan<- string)
readOnly := make(<-chan string)

人们使用类型(尤其是在 Go 中)的一个主要原因是作为一种文档形式。能够显示通道是只读的还是只写的,可以帮助 API 的消费者更好地了解正在发生的事情。

理论上,您可以使用只写通道进行单元测试,以确保您的代码不会向通道写入超过特定次数。

像这样:http://play.golang.org/p/_TPtvBa1OQ

package main

import (
    "fmt"
)

func MyCode(someChannel chan<- string) {
    someChannel <- "test1"
    fmt.Println("1")
    someChannel <- "test2"
    fmt.Println("2")
    someChannel <- "test3"
    fmt.Println("3")
}

func main() {
    writeOnly := make(chan<- string, 2) // Make sure the code is writing to channel jsut 2 times
    MyCode(writeOnly)
}

但这对于单元测试来说是非常愚蠢的技术。您最好创建一个缓冲通道并检查其内容。