douqi3913 2019-01-29 03:50
浏览 321
已采纳

`var a chan int`和`a:= make(chan int)`有什么区别?

Today I'm learning channels and goroutine of go. And I met some phenomenon which confuses me.

My go file looks like this:

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
", c, d)
}

it works well when I used syntax a := make(chan int).

But when I changed a := make(chan int) to var a chan int, I got panic report:

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

So, is there any difference between var a chan int and a := make(chan int), and why this panic phenomenon was triggered?

  • 写回答

3条回答 默认 最新

  • dst2017 2019-01-29 03:55
    关注

    Recall that var name type creates a variable named name of type type set to the default value for that type. This means that var a chan int creates a channel such that a == nil.

    var a chan int = make(chan int) and a := make(chan int) are, however, the same.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记