mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 05:11:49 +08:00
update book code
This commit is contained in:
45
eBook/exercises/chapter_14/gofibonacci3.go
Executable file
45
eBook/exercises/chapter_14/gofibonacci3.go
Executable file
@@ -0,0 +1,45 @@
|
||||
// courtesy of: http://sdh33b.blogspot.com/2009/12/fibonacci-in-go.html
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func dup3(in <-chan int) (<-chan int, <-chan int, <-chan int) {
|
||||
a, b, c := make(chan int, 2), make(chan int, 2), make(chan int, 2)
|
||||
go func() {
|
||||
for {
|
||||
x := <-in
|
||||
a <- x
|
||||
b <- x
|
||||
c <- x
|
||||
}
|
||||
}()
|
||||
return a, b, c
|
||||
}
|
||||
|
||||
func fib() <-chan int {
|
||||
x := make(chan int, 2)
|
||||
a, b, out := dup3(x)
|
||||
go func() {
|
||||
x <- 0
|
||||
x <- 1
|
||||
<-a
|
||||
for {
|
||||
x <- <-a + <-b
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
|
||||
func main() {
|
||||
start := time.Now()
|
||||
x := fib()
|
||||
for i := 0; i < 10; i++ {
|
||||
fmt.Println(<-x)
|
||||
}
|
||||
end := time.Now()
|
||||
delta := end.Sub(start)
|
||||
fmt.Printf("longCalculation took this amount of time: %s\n", delta)
|
||||
}
|
Reference in New Issue
Block a user