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.
}