Your Goroutine doesn't have enough time to execute, as the main function exits after printing Done!
.
You need to do something to make the program wait for the Goroutine.
The easiest way is to add a 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 the goroutine...
one
two
three
Done!
Playground
While this works, it's recommended to use channels, or functions from the sync
package, in addition to goroutines, to synchronize concurrent 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!")
}
Entering the goroutine...
received one
received two
received three
Done!
Playground