package main import ( "fmt" ) func main() { c := make(chan string) go fmt.Println(<-c) c <- "Hello World!" fmt.Println("Exit!") }
sobes.tech AI
Answer from AI
In this code, a string channel c := make(chan string) is created, which by default is unbuffered.
Then a goroutine go fmt.Println(<-c) is started, which attempts to read from the channel and print the received string.
After that, in the main goroutine, a string c <- "Hello World!" is sent to the channel.
Since the channel is unbuffered, the send operation blocks until another goroutine reads the value. In this case, the goroutine that reads from the channel is already running and waiting for data, so the exchange occurs correctly.
The output will be:
Hello World!
Exit!
The order is guaranteed because the main goroutine blocks on sending to the channel until the receiving goroutine reads the value. After that, the main thread continues and prints "Exit!".
If the channel were buffered, for example make(chan string, 1), then the reading goroutine could start later, but in this case, synchronization occurs through the unbuffered channel.