File tree Expand file tree Collapse file tree 3 files changed +64
-0
lines changed
Expand file tree Collapse file tree 3 files changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ package main
2+
3+ import "fmt"
4+
5+ func prod (c chan func ()) {
6+ f := <- c
7+ f ()
8+ c <- nil
9+ }
10+
11+ func main () {
12+ c := make (chan func ())
13+ go prod (c )
14+ x := 0
15+ c <- func () { // puts a closure in channel c
16+ x ++
17+ }
18+ fmt .Println (x )
19+ }
Original file line number Diff line number Diff line change 1+ package main
2+
3+ import (
4+ "fmt"
5+ "time"
6+ )
7+
8+ func FutureValue () <- chan int {
9+ ch := make (chan int )
10+ go func () {
11+ fmt .Println ("Computing in background..." )
12+ time .Sleep (2 * time .Second )
13+ ch <- 42 // Send result after delay
14+ }()
15+ return ch
16+ }
17+
18+ func main () {
19+ future := FutureValue ()
20+ fmt .Println ("Future started, doing other work..." )
21+
22+ // Do something else here...
23+
24+ result := <- future // Wait for future value
25+ fmt .Println ("Got future result:" , result )
26+ }
Original file line number Diff line number Diff line change 1+ package main
2+
3+ import "fmt"
4+
5+ // LazySum returns a function that calculates sum only when called
6+ func LazySum (a , b int ) func () int {
7+ return func () int {
8+ fmt .Println ("Evaluating sum now..." )
9+ return a + b
10+ }
11+ }
12+
13+ func main () {
14+ sum := LazySum (5 , 7 ) // Not yet evaluated
15+ fmt .Println ("Sum function created, not evaluated." )
16+
17+ result := sum () // Evaluated here
18+ fmt .Println ("Result:" , result )
19+ }
You can’t perform that action at this time.
0 commit comments