背景介绍
学习Go的时候,遇到了 make
和 new
的区别问题。网上查看了很多文档,大体都是4个区别(见下文),但是缺少更详细的说明和更丰富的代码样例。比如:
- zero value of the type(零值)
- 声明(declare)、分配内存空间(allocate)、初始化(initialize)、赋值,各自的作用
- 用 new 去给slice、map、chan进行内存分配,会是什么结果?
下面将先介绍官方文档里make
和new
的定义,然后讲解它们的不同点,最后
Talk is cheap. Show me the code.
make
func make(t 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、chan分配内存空间,并初始化一个对象。它的第一个参数是一个类型,第二个参数是一个可变长参数,返回的是这个类型本身。
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. For example, make([]int, 0, 10) allocates an underlying array
of size 10 and returns a slice of length 0 and capacity 10 that is
backed by this underlying array.
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.
- 对于 slice(切片) 类型,第一个 size 表示的是切片的长度,第二个 size 表示的是切片的容量。如果只给了一个size参数,则切片的容量等于其长度;
- 对于 map(字典)类型,只有一个size,表示给map分配一个多大的空间,如果忽略这个参数,则自动分配一个小空间(一般不需要这个参数,因为会map会自动扩展);
- 对于 chan(管道)类型,只有一个size,表示管道的缓冲区,无参数就是无缓冲区。
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.
new() 方法分配内存空间。它的第一个参数是一个类型,然后返回指向该类型的一个内存空间的指针。
make vs. new
make | new | |
---|---|---|
1 | 只用于slice、map、chan | 任意结构,包括slice、map、chan |
2 | 传入的参数包括一个类型,还有一个size | 只接收一个类型参数,没有size |
3 | 返回的是类型本身 | 返回的是类型的指针 |
4 | 分配内存空间,进行初始化 | 分配内存空间,不进行初始化 |
代码样例
上面总结了make
和new
的一些不同点,下面将针对这些不同点,以及最上面提到的一些问题,进行代码实验。
zero value of the type(零值)
零值是指创建一个变量后(也就是分配了内存空间之后),并没有给该变量一个初始值,那么Go会自动用零值对该变量进行初始化。
Type | 零值 |
---|---|
int, int32, int64 | 0 |
float32, float64 | 0.0 |
string | "" |
bool | false |
pointer, function, interface, slice, channel, map | nil |
数组, struct | 递归初始化为零值 |
注意:数组的零值是递归初始化数组元素类型的零值,而切片的零值是nil
Go的零值在这篇文章中被吐槽了。
type TT struct {
A string
B int64
C struct {
Cd string
Ce string
Cf []float64
}
G bool
H float32
}
func main() {
var i *[]int
i = new([]int)
fmt.Println(i, len(*i), cap(*i)) // &[] 0 0
var istring *[]string
istring = new([]string)
fmt.Println(istring, len(*istring), cap(*istring)) // &[] 0 0
var tt = new(TT)
fmt.Println(tt) // &{ 0 { []} false 0}
}
declare、allocate、initialize、赋值
// 1. 声明 declare
var i *int
var tt *TT
// 2. 分配内存 allocate
i = new(int)
tt = new(TT)
// 声明 + 分配内存
var i = new(int)
var i *int = new(int)
i := new(int)
var tt = new(TT)
var tt *TT = new(TT)
tt := new(TT)
tt := &TT{}
// 3. 初始化 initialize
// 初始化就是第一次赋值
var arr = make([]int, 3) // arr => [0, 0, 0]
// 4. 赋值
i = 4
tt = TT{A: "a", B: 12, ...}
// 声明 + 赋值
i := TT{A: "a", B: 12, ...}
用new去给 slice、map、chan进行内存分配
用new对map、chan进行内存分配,效果和make差不多。
但是对slice进行内存分配时:
var i *[]int
i = new([]int)
fmt.Println(i, len(*i), cap(*i)) // &[] 0 0
j := make([]int, 3)
fmt.Println(j, len(j), cap(j)) // [0 0 0] 3 3
本来 slice的零值是 nil,但是 make 会做一次初始化,就变成了 [0 0 0]了。
而且 make 的第二个参数是不可以省略的,但是可以设置为0,这样的话:
j := make([]int, 0)
fmt.Println(j, len(j), cap(j)) // [] 0 0
总结
-
make
只用于 slice、map、channel 的内存分配,new
用于各种类型; -
new
返回指针 -
make
比new
多一些参数
相对而言,make
的功能和使用场景都是很明确的,而 new
的话:
- 如果是基础类型,如int,string,不需要使用 new
- 如果是基础类型的指针,在使用该指针(打印,赋值等)前,必须先分配内存空间,就可以用到 new 了。但是如果直接给从一个变量那里取地址赋值给它,就又不需要 new 了。
var pInt *int
pInt = new(int)
等价于
var i int = 10
var pInt *int = &i
fmt.Println(*pInt) // 10
- 如果是数组、切片、结构体、map类型的指针,也是类似:
var s *[3]int
s = new([3]int)
等价于
var s *[3]int = &[3]int{}
var s *[]int
s = new([]int)
等价于
var s *[]int = &[]int{}
var t *TT
t = new(TT)
等价于
var t *TT = new(TT)
等价于
var t *TT = &TT{}
var mp = new(map[string]string)
等价于
mp := map[string]string{}
注:chan 不能这么玩(也可能是我没找对姿势)
那么问题来了,为啥要有 new
呢?
如果有了解的朋友,希望能指点一下,多谢!
PS. 有一个思路是,多看看源码,看看哪里用到了new,以及是怎么使用new的,或许能对new有更深入的了解。
参考文档
- http://docs.studygolang.com/doc/effective_go.html#allocation_new
- http://docs.studygolang.com/doc/effective_go.html#allocation_make
- http://docs.studygolang.com/doc/faq#new_and_make
- https://studygolang.com/articles/3496
- http://www.jb51.net/article/126703.htm
-
https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.2.md
(这个文档也对 make 和 new 进行了对比,也解释了零值)
网友评论