Go‘s built-in new and make functions

Source:
Go has both make and new functions, what gives?

Digest:
1. Why can’t we use make for everything?
Although make creates generic slice, map, and channel values, they are still just regular values; make does not return pointer values.
If new was removed in favour make, how would you construct a pointer to an initialised value?

var x1 *int
var x2 = new(int)

x1 and x2 have the same type, *int, x2 points to initialised memory and may be safely dereferenced, the same is not true for x1.
2. Why can’t we use new for everything?
Although the use of new is rare, its behaviour is well specified.
new(T) always returns a *T pointing to an initialised T. As Go doesn't have constructors, the value will be initialised to T's zero value.
Using new to construct a pointer to a slice, map, or channel zero value works today and is consistent with the behaviour of new.

s := new([]string)
fmt.Println(len(*s))	// 0
fmt.Println(*s == nil)	// true

m := new(map[string]string)
fmt.Println(m == nil)	// false
fmt.Println(*m == nil)	// true

c := new(chan int)
fmt.Println(c == nil)	// false
fmt.Println(*c == nil)	// true

3. Sure, but these are just rules, we can change them, right?
For the confusion they may cause, make and new are consistent; make only makes slices, maps, and channels, new only returns pointers to initialised memory.
4. In summary:
make and new do different things.
My advice is to use new sparingly, there are almost always easier or cleaner ways to write your program without it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值