dongtan8532 2018-03-01 17:59 采纳率: 0%
浏览 1
已采纳

创建频道时,新vs制作[重复]

This question already has an answer here:

In Go, I read document and understand basic differences between make and new

  • new: return a pointer (*T) and zeros value it points to
  • make: return type T

I read document and mostly example using array. I understand new vs make when creating array. But I don't understand differences when creating channel:

c1 := new(chan string)
c2 := make(chan string)

What is real differences except that c1 has type (chan*) and c2 has type chan.

Thanks

</div>
  • 写回答

1条回答 默认 最新

  • donglun2010 2018-03-01 18:06
    关注

    The behavior of new is explained in Allocation with new.

    It's a built-in function that allocates memory, but unlike its namesakes in some other languages it does not initialize the memory, it only zeros it.

    In this case new(chan string) returns a pointer to a zero value of type chan string, which is the nil channel. The following program deadlock as it tries to read from a nil channel.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        c1 := new(chan string)
        fmt.Println(*c1)
        go func() {
            *c1 <- "s"
        }()
        fmt.Println(<-*c1)
    }
    

    With make(chan string) you get an actual usable channel, not a zero value of channel type.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        c2 := make(chan string)
        fmt.Println(c2)
        go func() {
            c2 <- "s"
        }()
        fmt.Println(<-c2)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析