Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of channel communication with a simple select statement. Taken from Rob Pike's slides about concurrency in Go.
package main
import (
"fmt"
"time"
)
func boring(msg string) <-chan string { // Returns receive-only channel of strings.
c := make(chan string)
go func() { // We launch the goroutine from inside the function.
for i := 0; ; i++ {
c <- fmt.Sprintf("%s %d", msg, i)
time.Sleep(400 * time.Millisecond)
}
}()
return c // Return the channel to the caller.
}
func main() {
c := boring("Joe")
timeout := time.After(2 * time.Second)
for {
select {
case s := <-c:
fmt.Println(s)
case <-timeout:
fmt.Println("You talk too much.")
return
}
}
}
@Veejay

This comment has been minimized.

Copy link
Owner Author

commented Jan 18, 2013

  1. The channel is returned to the main before the boring function finishes
  2. The time.After function actually returns a channel on which the current time will be sent after the specified interval.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.