Skip to content

Instantly share code, notes, and snippets.

@riston
Last active January 9, 2016 11:27
Show Gist options
  • Save riston/1af1cbbcd672b063616a to your computer and use it in GitHub Desktop.
Save riston/1af1cbbcd672b063616a to your computer and use it in GitHub Desktop.
Go patterns
package main
import (
"fmt"
"time"
)
// Function blocks the execution until the heavy execution is done
func heavySum(a, b int) chan int {
future := make(chan int, 1)
go func() {
time.Sleep(5 * time.Second)
future <- (a + b)
}()
return future
}
func main() {
fmt.Println("Block until work is done?")
fmt.Println("Blocks", <-heavySum(12, 12))
fmt.Println("After")
}
package main
import (
"fmt"
"time"
)
func numGen(to int) chan int {
yield := make(chan int)
go func() {
index := 0
for index <= to {
time.Sleep(3 * time.Second)
yield <- index
index++
}
close(yield)
}()
return yield
}
func main() {
numbers := numGen(30)
for cur := range numbers {
fmt.Println("->", cur)
}
fmt.Println("After")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment