Last active
January 9, 2016 11:27
-
-
Save riston/1af1cbbcd672b063616a to your computer and use it in GitHub Desktop.
Go patterns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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