在 Go 中,可以创建单向通道。如果您想限制给定频道上可用的一组操作,这是一个非常方便的功能。然而,据我所知,这个特性只对函数的参数和变量的类型规范有用,而通过创建单向通道make对我来说看起来很奇怪。我读过这个问题,但这不是关于在 Go 中创建只读(或写)通道,而是关于一般使用。所以,我的问题是关于下一个代码的用例:writeOnly := make(chan<- string)readOnly := make(<-chan string)
2 回答

海绵宝宝撒
TA贡献1809条经验 获得超8个赞
从理论上讲,您可以使用只写通道进行单元测试,以确保例如您的代码写入通道的次数不会超过特定次数。
像这样的东西: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)
}
但这对于单元测试来说是非常愚蠢的技术。您最好创建一个缓冲通道并检查其内容。
- 2 回答
- 0 关注
- 187 浏览
添加回答
举报
0/150
提交
取消