Your Goroutine does not have enough time to complete, since the main function ends after printing Done! .
You need to do something to make the program expect Goroutine.
The easiest way is to add time.Sleep() to the end.
package main import ( "fmt" "time" ) func main() { messages := make(chan string, 3) messages <- "one" messages <- "two" messages <- "three" go func(m *chan string) { fmt.Println("Entering the goroutine...") for { fmt.Println(<-*m) } }(&messages) time.Sleep(5 * time.Second) fmt.Println("Done!") }
Entering goroutine ... alone
two
three
Done!
Playground
While this works, it is recommended that you use the channels or functions from the sync package, in addition to goroutines, to synchronize parallel code.
Example:
package main import ( "fmt" ) func main() { messages := make(chan string, 3) go func(m chan string) { defer close(m) fmt.Println("Entering the goroutine...") messages <- "one" messages <- "two" messages <- "three" }(messages) for message := range messages { fmt.Println("received", message) } fmt.Println("Done!") }
Joining Gorutin ... got one got two
got three done!
Playground
Intermernet
source share