You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言中new与make创建channel的核心差异咨询

new vs make for Channels in Go: Beyond Return Types

Great question! Let's cut through the type declaration differences and get to the practical, real-world behavior that matters when working with channels.

What happens when you use new(chan T)?

When you call new(chan int), you're asking Go to:

  • Allocate memory for a channel variable (not an actual usable channel)
  • Set that variable to its zero value (nil)
  • Return a pointer to this nil variable (*chan int)

The problem here is that this nil channel isn't initialized—it has no underlying buffer, no synchronization structures, and it's completely unusable for sending or receiving data. If you try to dereference the pointer and perform operations on it, you'll hit a permanent block (since operations on nil channels never complete).

Here's what that looks like in code:

c1 := new(chan int)
// ❌ This will block forever—*c1 is a nil channel
// <-*c1

// You have to manually assign an initialized channel to the pointer to make it work:
*c1 = make(chan int)
// Now this works
go func() { *c1 <- 42 }()
fmt.Println(<-*c1)

What happens when you use make(chan T, bufferSize)?

make is specifically designed for initializing Go's reference types (slices, maps, and channels). When you call make(chan int) or make(chan int, 5), Go does two key things:

  • Allocates memory for the channel's underlying data structures (like a buffer queue and synchronization primitives)
  • Initializes those structures so the channel is ready to use immediately
  • Returns the channel itself (chan int), not a pointer

You can start sending and receiving data right away without any extra steps:

c2 := make(chan int)
// ✅ This works immediately
go func() { c2 <- 123 }()
fmt.Println(<-c2)

// With a buffered channel
c3 := make(chan string, 2)
c3 <- "hello"
c3 <- "world"
fmt.Println(<-c3) // Prints "hello"

The Core Practical Difference

  • new gives you a pointer to a nil channel—useless on its own, requiring an extra make call to become functional. There's almost no scenario where you'd want to do this for channels; it's unnecessary extra work.
  • make gives you a fully initialized, ready-to-use channel in one step. This is the standard, idiomatic way to create channels in Go.

内容的提问来源于stack exchange,提问作者Trần Kim Dự

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 06:55:08