首页 > 技术文章 > Go语言中new和make的区别

wind-zhou 2020-05-03 11:44 原文

Go语言中new跟make是内置函数,主要用来创建分配类型内存。

new( )

new(T)创建一个没有任何数据的类型为T的实例,并返回该实例的指针;

源码解析

func new
func new(Type) *Type
The new built-in function allocates memory. The first argument is a type, not a value, and the value returned is a pointer to a newly allocated zero value of that type.

make( )

make(T, args)只能创建 slice、map和channel,并且返回一个有初始值args(非零)的T类型的实例,非指针。

源码解析

func make
func make(Type, size IntegerType) Type
The make built-in function allocates and initializes an object of type slice, map, or chan (only). Like new, the first argument is a type, not a value. Unlike new, make's return type is the same as the type of its argument, not a pointer to it. The specification of the result depends on the type:

二者异同

二者都是内存的分配(堆上),但是make只用于slice、map以及channel的初始化(非零值);而new用于类型的内存分配,并且内存置为零。所以在我们编写程序的时候,就可以根据自己的需要很好的选择了。

推荐阅读