package main
import (
"fmt"
"time"
)
func fib() chan int {
c := make(chan int)
go func() {
c <- 0
c <- 1
n, m := 0, 1
for {
temp := n + m
n = m
m = temp
c <- m // This results in panic, when the channel is closed
}
}()
return c
}
func main() {
start := time.Now()
var lastFib int
c := fib()
for i := 0; i != 1000000; i++ {
lastFib = <-c
}
close(c)
fmt.Println(lastFib)
fmt.Println(time.Now().Sub(start))
}
以最習慣的方式,當通道關閉時,如何避免在goroutine中發生恐慌?或者我應該避免使用close
?當試圖向封閉通道插入值時,避免恐慌
我沒有尋找替代方法(如閉包)來實現同樣的事情,只是試圖更好地理解渠道。