今天在学习go的channels和goroutine。我遇到了一些让我困惑的现象。
我的 go 文件如下所示:
package main
import (
"fmt"
)
func testRoutine(number int, channel chan int) {
channel <- number
}
func main() {
// var a chan int
a := make(chan int)
b := make(chan int)
go testRoutine(1, a)
go testRoutine(2, b)
c, d := <-a, <-b
fmt.Printf("%d %d\n", c, d)
}
当我使用 syntax 时效果很好a := make(chan int)。
但是当我更改a := make(chan int)为时var a chan int,我收到了 panic 报告:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive (nil chan)]:
main.main()
/Users/marioluisgarcia/Local/practice/go/cache/var_make_diff.go:19 +0xc7
goroutine 18 [chan send (nil chan)]:
main.testRoutine(0x1, 0x0)
/Users/marioluisgarcia/Local/practice/go/cache/var_make_diff.go:8 +0x3f
created by main.main
/Users/marioluisgarcia/Local/practice/go/cache/var_make_diff.go:16 +0x7c
goroutine 19 [chan send]:
main.testRoutine(0x2, 0xc42008a060)
/Users/marioluisgarcia/Local/practice/go/cache/var_make_diff.go:8 +0x3f
created by main.main
/Users/marioluisgarcia/Local/practice/go/cache/var_make_diff.go:17 +0xa7
var a chan int那么,和有什么区别a := make(chan int),为什么会引发这种恐慌现象呢?
侃侃无极
慕尼黑的夜晚无繁华
吃鸡游戏
相关分类