# Go语言中new和make的区别

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:

Slice: The size specifies the length. The capacity of the slice is
equal to its length. A second integer argument may be provided to
specify a different capacity; it must be no smaller than the
length, so make([]int, 0, 10) allocates a slice of length 0 and
capacity 10.
Map: An empty map is allocated with enough space to hold the
specified number of elements. The size may be omitted, in which case
a small starting size is allocated.
Channel: The channel's buffer is initialized with the specified
buffer capacity. If zero, or the size is omitted, the channel is
unbuffered.



### 二者异同

make返回的还是这三个引用类型本身；而new返回的是指向类型的指针。

posted @ 2019-11-19 22:16  haleyrom  阅读(410)  评论(0编辑  收藏