// 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. funcmake(t Type, size ...IntegerType)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. funcnew(Type) *Type
new 内置函数分配内存。第一个参数是类型,而不是值,返回的值是指向该类型新分配的零值的指针。
new 不常用:new 在一些需要实例化接口的地方用的较多,但是可以用 &A{} 代替。
但是 new 和 &A{} 也是有差别的,主要差别在于 &A{} 显示执行堆分配。
make 也是用于内存分配的,但是和 new 不同,它只用于 slice ,map 以及 channel 的内存创建,而且它返回的类型就是这三个类型本身,而不是它们的指针类型,因为这三种类型就是引用类型,所以就没必要返回它们的指针了。
funcmain() { a := new([]int) fmt.Println(a) // &[] fmt.Println(a != nil) // true , 是该类型的零值,并不是nil (*a)[0] = 18//panic: runtime error: index out of range [0] with length 0