制作单向通道有什么目的?

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

Is there a purpose for "make"ing a one-directional channel?

问题

NB:这不是这个问题的重复,因为我理解何时使用单向通道。我一直这样做。我的问题是为什么这个程序是有效的:

func main() {
    ch := make(chan<- int)
    ch <- 5
    fmt.Println("Hello, playground")
}

Playground

运行它,当然会导致死锁。如果你用%T检查类型,Go实际上会报告ch的类型是一个只发送的通道。在Go中,你可以使用make创建单向通道,但这没有太多意义,因为通过创建一个在初始时只能单向传输的通道,你确保至少一个读/写操作永远不会发生。

一个可能的解释是强制一个goroutine挂起,但是使用select {}同样容易实现。

我唯一的其他想法是强制一个goroutine只执行n次操作:

ch := make(chan<- int, 50)
// 做50次操作,因为缓冲区已满
for {
    ch <- doSomething()
}

但是这更容易实现,而且更不容易引起混淆,可以使用许多不同的结构来实现。

这只是类型系统的一个怪癖/疏忽,还是我没有考虑到这种行为的用途?

英文:

NB: This is not a duplicate of this question, because I understand when you would use one-directional channels. I do so all the time. My question is why this program is valid:

func main() {
	ch := make(chan&lt;- int)
	ch &lt;- 5
	fmt.Println(&quot;Hello, playground&quot;)
}

Playground

Running it, of course, gives a deadlock. If you check the type with %T, Go does in fact report that the type of ch is a send-only channel. In Go, you're allowed to make uni-directional channels, but it makes little sense because by making a channel that at its inception is one-way only, you're ensuring at least one of read/write will never occur.

A possible explanation would be to force a goroutine to hang but that's just as easily accomplished with select {}.

My only other idea is to force a goroutine to only do something n times,

ch := make(chan&lt;- int, 50)
// do something 50 times, since then the buffer is full
for {
  ch &lt;- doSomething()
}

But that's more easily, not to mention less confusingly, accomplished with any number of different constructions.

Is this just a quirk/oversight of the type system, or is there use for this behavior I'm not thinking of?

答案1

得分: 4

你有一种语言:单词(标记)和语法。你总是可以写出有效的胡言乱语:蓝色不是一种颜色。

你写了一些有效的胡言乱语:

package main

func main() {
	ch := make(chan&lt;- int)
	ch &lt;- 5
}

这里还有一些有效的胡言乱语:

package main

func main() {
	for {
	}
}
英文:

You have a language: words (tokens) and a grammar. You can always write valid nonsense: blue is not a color.

You wrote some valid nonsense:

package main

func main() {
	ch := make(chan&lt;- int)
	ch &lt;- 5
}

Here's some more valid nonsense:

package main

func main() {
	for {
	}
}

huangapple
  • 本文由 发表于 2015年7月6日 15:15:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/31239758.html
匿名

发表评论

匿名网友

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

确定