new和make都是golang的内建函数,都用于分配内存
make
先看一下make函数的定义
// 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 或 chan 类型分配内存和初始化一个对象,跟 new 类似,第一个参数是一个类型而不是一个值,跟 new 不同的是,make 返回类型的引用而不是指针,返回值依赖于具体传入的类型。
new
先看一下make函数的定义
// 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 用来分配内存,第一个参数是一个类型,不是一个值,返回值是一个指向新分配类型零值的指针
区别
package main
import (
"fmt"
)
func main(){
a:=new([10]int) // a是指针
b:=make([]int,10) // b是引用
fmt.Printf("a type: %T, value: %v\n",a,*a)
fmt.Printf("b type: %T, value: %v\n",b,b)
}
运行结果
a type: *[10]int, value: [0 0 0 0 0 0 0 0 0 0]
b type: []int, value: [0 0 0 0 0 0 0 0 0 0]
总结:
new会分配结构空间,并初始化为清空为零,不进一步初始化
new之后需要一个指针来指向这个结构
new分配返回的是指针
make会分配结构空间及其附属空间,并完成其间的指针初始化
make返回这个结构空间,不另外分配一个指针
make分配返回的是引用