29

【Golang小知识】new与make的区别

 4 years ago
source link: https://studygolang.com/articles/24731
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

定义

func new(Type) *Type
func make(t Type, size ...IntegerType) Type

其中Type代表某一个数据类型。

区别

1.返回值

从定义中可以看出,new返回的是指向Type的指针。

make直接返回的是Type类型值。

2.入参

new只有一个Type参数,Type可以是任意类型数据。

make可以有多个参数,其中第一个参数与new的参数相同,但是只能是slice,map,或者chan中的一种。对于不同类型,size参数说明如下:

  • 对于slice,第一个size表示长度,第二个size表示容量,且容量不能小于长度。如果省略第二个size,默认容量等于长度。
  • 对于map,会根据size大小分配资源,以足够存储size个元素。如果省略size,会默认分配一个小的起始size。
  • 对于chan,size表示缓冲区容量。如果省略size,channel为无缓冲channel。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK