I'm a bit confused about the difference between buffered and unbuffered channels in Go. For example, the below code executes fine:
package main
import "fmt"
func main() {
messages := make(chan string)
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
On the other hand, when I pass "ping" to messages in a regular function, there is a deadlock.
package main
import "fmt"
func main() {
messages := make(chan string)
func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
Finally, this is fixed when I use a buffered channel, like so
package main
import "fmt"
func main() {
messages := make(chan string, 1)
func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
I'm confused why the second case failed. Go By Example says that
By default channels are unbuffered, meaning that they will only accept sends (chan <-) if there is a corresponding receive (<- chan) ready to receive the sent value. Buffered channels accept a limited number of values without a corresponding receiver for those values.
In all three cases, isn't msg the sink for messages?