Skip to content

Commit c2f62e7

Browse files
committed
anonymous closure,lazyevaluation and future with go lang
1 parent b135b5e commit c2f62e7

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
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+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
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+
}

0 commit comments

Comments
 (0)