Goroutines outlive their calling function
While watching a talk by Rob Pike I learned today something about Goroutines which surprised me: Goroutines outlive their calling function. Said another way, if the function which created the goroutine returns, the goroutine will continue running. (main() is the one exception.) This is fantastic! 🎉 Here’s an example of this in practice. package main import ( "fmt" "time" ) func person(msg string) <-chan string { // Function returns a receive-only channel ch := make(chan string) // Create unbuffered channel go func() { // This goroutine lives on after person() returns for i := 0; ; i++ { time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) ch <- fmt.Sprintf("%s %d", msg, i) } }() return ch } func main() { james := person("james") // Assign returned channel to variable sinah := person("sinah") for i := 0; i < 5; i++ { fmt.Println(<-james) // Block, waiting for value on channel fmt.Println(<-sinah) } fmt.Println("Done!") } Output: ...