为什么相同的 Go 通道不能被启动两次?

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

Why same Go Channel can't be started twice?

问题

在Go语言中,不能重复使用已声明的通道。如果尝试两次使用同一个通道,会得到该通道的默认值。因此,如果要再次使用通道,需要声明另一个通道。这是Go语言的设计选择,旨在确保通道的正确使用和避免潜在的错误。

英文:

Can we start the one decalred channel twice in Go lang ?

package main

import (
    "fmt"
)

func emit(c chan string) {
    
    words := []string {"The", "quick", "brown", "fox"}
    
    for _, word := range  words {
        c <- word
    }
    close(c)
}

In the function main If i try to use the same channel twice i'm getting default value of that channel

func main() {
 
    wordChannel := make(chan string)
    
    go emit(wordChannel)
    
    for word := range wordChannel {
        fmt.Printf("%s ", word)
    }
        
    go emit(wordChannel)
    word1 := <-wordChannel
    fmt.Printf("%s" , word1) // prints Default value
}

Output

So to use it again i've to declare another channel.
If this is not an error why this was done in the Go Lang. ?
i'm using go -lang version 1.6

答案1

得分: 6

通道并不是“启动”的,通道只是存在,并处于以下两种状态之一:

  • “打开”状态,此时您可以向其发送值(并接收发送的值)。
  • “关闭”状态,此时您无法发送值,并且从关闭的通道接收值会返回“零值,false”。

一旦通道关闭,它将永远保持关闭状态。因此,在Go语言中,您必须创建一个新的通道,而没有“重新打开”的操作。

英文:

Channels are not "started", channels simply exist and are in one of two states:

  • "open" in which case you can send values to them (and receive the values sent), or
  • "closed" in which you cannot send and receiving from a closed channel results in "the-zero-value, false".

A once closed channel stays closed forever. So yes, you have to make a new channel, there is no "reopen" in Go.

huangapple
  • 本文由 发表于 2016年11月14日 19:20:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/40587553.html
匿名

发表评论

匿名网友

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

确定