Skip to content

Instantly share code, notes, and snippets.

@Veejay
Created January 18, 2013 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Veejay/4562695 to your computer and use it in GitHub Desktop.
Save Veejay/4562695 to your computer and use it in GitHub Desktop.
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
Copy link
Author

Veejay 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