Channel send and receive on func main()

Viewed 147

I've been learning channels and the text book examples seem simple and easy to understand. However, i'm unable to understand the following behavior.

func main() {
     message := make(chan string)

     message <- "ping"
     fmt.Println(<-message)
}

Why does the above result in error? I understand i can make it work by introducing a go routine to have both sender and receiver ready. However, if that's the case, why does the following work.

func main() {
    message := make(chan string,1)

    message <- "ping"
    fmt.Println(<-message)

}

*********Thanks Joe McMahon for your answer*********
*********Documenting below for my reference*********
I assumed a buffer of 1(unlike 2) would also block the main routine until it finds a corresponding receiver. It seems like a buffer of 1 works like 0 & 1 and doesn't block the code for the 0th write/read. To demonstrate a block using buffers,

func main() {
    message := make(chan string, 1)

    message <- "ping1"
    message <- "ping2"
    fmt.Println(<-message) //Unreachable code.
}
1 Answers

Adding the ',1' buffers the channel. That means that one write to the channel is non-blocking, and the main program retains control. If the channel is not buffered, then the writing program blocks until another goroutine gets control and reads from the channel.

The program has dropped the string into the buffered channel; it now keeps running, reads the string out of the buffered channel, and prints it, never having blocked.

If you use a goroutine and an unbuffered channel:

  • The goroutine starts, reads from the channel, and blocks, waiting for something to be written to the channel.
  • The main program writes to the channel and blocks, waiting for someone to read the string just written.
  • The Go dispatcher looks for a routine eligible to run, finds the goroutine with a string ready to be read from the channel. It returns control to the goroutine, which receives the string and proceeds.
  • When that goroutine exits or does something else that makes it lose control, the dispatcher looks for another program ready to run and sees the main program has successfully completed its write to the channel (the string has been read by the goroutine). The dispatcher gives control to the main program.
  • The main program completes and exits.
Related