英文:
Golang compiles with sends to nil channels
问题
我想知道Go语言是否可以编译并在发送到nil通道时运行。一个例子是:
func main() {
var ch chan string
var msg string
msg = "echo"
ch <- msg
msg = <-ch
}
这段代码可以编译通过,但是因为没有分配通道,只是一个nil值,所以它应该能够编译通过吗?直到你执行它时才会发现问题,更糟糕的是,有些集成开发环境(IDE)不会告诉你这是一个问题。
英文:
I wanted to know if GoLang is supposed to compile and run with sends to nil
channels. An example is:
func main() {
var ch chan string
var msg string
msg ="echo"
ch <-msg
msg = <-ch
}
That compiles but should it since there is no channel assigned just a nil. You don't discover there is a problem until you execute it and worse some IDEs dont tell you this is a problem.
答案1
得分: 3
一般情况下,这不能在编译时检测到。一个通道可能是一个函数的参数,传递的值可能只能在运行时决定。
因此,没有理由将其作为编译时错误。它可以是一个警告,但只适用于所有可能情况的一小部分。在某些情况下发出警告但不在所有情况下发出警告会产生误导。当你看不到警告时,你会得出错误的结论。更不用说有时使用/传递nil
通道可能是正确/预期的操作。
参考链接:https://stackoverflow.com/questions/39015602/how-does-a-non-initialized-channel-behave/39016004#39016004
英文:
In general this can't be detected at compile time. A channel may be an argument to a function, and what value is passed may only be decided at runtime.
So there is no reason to make this a compile time error. It could be a warning, but only at a small slice of all possible cases. It would be misleading to warn in some cases but not in all cases. You would draw the wrong conclusion when you see no warning. Not to mention using / passing a nil
channel may be the correct / intended thing to do sometimes.
See related: https://stackoverflow.com/questions/39015602/how-does-a-non-initialized-channel-behave/39016004#39016004
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论