golang new make 区别

本文详细解析了Go语言中make与new的功能差异。new为各种类型分配零值填充的内存并返回其地址;而make仅用于slice、map和channel的创建,并返回已初始化的值。了解这些差异对于正确使用Go语言进行内存管理至关重要。

make用于内建类型(map、slice 和channel)的内存分配

new用于各种类型的内存分配

 

new(T)分配了零值填充的T类型的内存空间, 并且返回其地址,即一个*T类型的值

 

内建函数make(T, args)与new(T)有着不同的功能,
make只能创建slice、map和channel,
并且返回一个有初始值(非零)的T类型,而不是*T

 

本质来讲,导致这三个类型有所不同的原因是指向数据结构的引用在使用前必须被初始化

 

The way to go

new(T) allocates zeroed storage for a new item of type T and returns its address,
a value of type *T:

   it returns a pointer to a newly allocated zero value of type T, 

ready for use;

     it applies to value types like arrays and structs (see Chapter 10);
it is equivalent to &T{ }


make(T) returns an initialized value of type T;
  it applies only to the 3 built-in reference types:
slices, maps and channels (see chapters 8 and 13).

 

 

转载于:https://www.cnblogs.com/allenhaozi/p/8684334.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值