猿问

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

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


writeOnly := make(chan<- string)

readOnly := make(<-chan string)


慕婉清6462132
浏览 188回答 2
2回答

海绵宝宝撒

从理论上讲,您可以使用只写通道进行单元测试,以确保例如您的代码写入通道的次数不会超过特定次数。像这样的东西:http : //play.golang.org/p/_TPtvBa1OQpackage mainimport (&nbsp; &nbsp; "fmt")func MyCode(someChannel chan<- string) {&nbsp; &nbsp; someChannel <- "test1"&nbsp; &nbsp; fmt.Println("1")&nbsp; &nbsp; someChannel <- "test2"&nbsp; &nbsp; fmt.Println("2")&nbsp; &nbsp; someChannel <- "test3"&nbsp; &nbsp; fmt.Println("3")}func main() {&nbsp; &nbsp; writeOnly := make(chan<- string, 2) // Make sure the code is writing to channel jsut 2 times&nbsp; &nbsp; MyCode(writeOnly)}但这对于单元测试来说是非常愚蠢的技术。您最好创建一个缓冲通道并检查其内容。

交互式爱情

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

相关分类

Go
我要回答