0

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.

erik258
  • 14,701
  • 2
  • 25
  • 31
  • 3
    Yes, Go will compile just fine. However *"a send on a nil channel blocks forever"*. See: https://go.dev/ref/spec#Send_statements – mkopriva Dec 03 '21 at 18:04
  • 1
    As does receive on a nil channel https://go.dev/ref/spec#Receive_operator. With a valid channel, your code deadlocks because there's nothing ready to receive the msg you're sending to the channel with `ch <- msg`. – erik258 Dec 03 '21 at 18:11

1 Answers1

3

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: How does a non initialized channel behave?

icza
  • 389,944
  • 63
  • 907
  • 827