Send statements

April 16, 2024

Send statements

A send statement sends a value on a channel. The channel expression’s core type must be a channel, the channel direction must permit send operations, and the type of the value to be sent must be assignable to the channel’s element type.

SendStmt = Channel "<-" Expression .
Channel  = Expression .

Both the channel and the value expression are evaluated before communication begins. Communication blocks until the send can proceed. A send on an unbuffered channel can proceed if a receiver is ready. A send on a buffered channel can proceed if there is room in the buffer. A send on a closed channel proceeds by causing a run-time panic. A send on a nil channel blocks forever.

ch <- 3  // send value 3 to channel ch

We’ve talked about channels before (and we will again), so there’s not a whole lot of new information here. But it’s a good chance to recap a bit.

Perhaps obvious, but it’s good to note what it says about evaluation order: “Both the channel and the value expression are evaluated before communication begins.” Really, this follows from what we’ve already learned about initialization dependencies. Just as you can’t assign to, say, a slice, without first evaluating the slice and the value to assign to it, you can’t send on a channel without first evaluating the channel and value expressions.

The most important thing about sending on channels, and most confusing for newcomers, is the blocking behavior. “Communication blocks until the send can proceed.”

The rest of the description elaborates on the possible scenarios:

  • A send on an unbuffered channel blocks until the receiver is ready.
  • A send on a buffered channel blocks until there is room in the buffer.
  • A send on a closed channel panics.
  • A send on a nil channel blocks forever.

As simple as this may appear in isolation, there’s still a lot of room for confusion, because you never send on a channel in isolation. There’s always the receiving side. And sometimes there’s more than one sender or more than one receiver. It’s the combinations that have the potential to make this confusing.

If you have a confusing channel situation you’d like some help with, would you share it with me? I’ll try to discuss it on the list in the future (please only send code you’re willing for me to share!)

Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe