mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 05:11:49 +08:00
47 lines
713 B
Go
Executable File
47 lines
713 B
Go
Executable File
// 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
|
|
}
|
|
}()
|
|
<- out
|
|
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)
|
|
}
|