在Go语言中创建单向通道的目的是什么?

huangapple go评论82阅读模式
英文:

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

问题

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

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

In Go one can create one-way channels. It's a very convenient feature in case of one want to restrict a set of operations available on the given channel. However, as far as I can see, this feature is useful only for function's arguments and variable's type specification, while creating one-way channels via make looks strange for me. I've read this question, but it's not about creating read (or write)-only channels in Go, it's about usage in general. So, my question is about use cases of the next code:

writeOnly := make(chan&lt;- string)
readOnly := make(&lt;-chan string)

答案1

得分: 4

理论上,你可以使用只写通道(write only channels)进行单元测试,以确保你的代码不会向通道写入超过特定次数的内容。

类似这样的代码: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) // 确保代码只向通道写入2次
	MyCode(writeOnly)
}

但这对于单元测试来说是相当愚蠢的技术。更好的方法是创建一个带缓冲的通道并检查其内容。

英文:

Theoretically you can use write only channels for unit testing to ensure for example that your code is not writing more than specific number of times to a channel.

Something like this: http://play.golang.org/p/_TPtvBa1OQ

package main

import (
	&quot;fmt&quot;
)

func MyCode(someChannel chan&lt;- string) {
	someChannel &lt;- &quot;test1&quot;
	fmt.Println(&quot;1&quot;)
	someChannel &lt;- &quot;test2&quot;
	fmt.Println(&quot;2&quot;)
	someChannel &lt;- &quot;test3&quot;
	fmt.Println(&quot;3&quot;)
}

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

But that would be pretty silly technique for unit testing. You're better to create a buffered channel and check its contents.

答案2

得分: 0

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

英文:

One of the main reason that people use types (especially in Go) is as a form of documentation. Being able to show that a channel is read-only or write-only, can help the consumer of the API have a better idea of what is going on.

huangapple
  • 本文由 发表于 2016年4月23日 00:06:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/36798580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定