New or Make

new()和make()的区别

New和Make的区别

以下是Go1.19中对new()和make()函数的解释:

1
2
3
4
// 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.
func new(Type) *Type

new()是一个新的分配内存的函数,第一个参数是类型,不是值,返回的值是指向该类型零值的指针。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// 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. 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.
func make(t Type, size ...IntegerType) Type

make()函数用于初始化slice,map和channel。和new()比较像的是第一个参数也是一个类型,不是值。区别于new的地方在于make()返回的值和他参数类型是一样的。第二个类型size是一个可变长类型的参数,作用如下:

1
2
3
4
    m := make(map[int]string, 5)
    s := make([]int, 5, 10)
    channel := make(chan string, 5)
    fmt.Println(m, s, channel)

初始化一个slice,传入第一个参数为类型,第二个参数为长度,第三个参数为容量,容量不可以小于长度。初始化map的可变参数只有容量cap,而初始化channel的可变参数为缓冲大小。

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计