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
new的原型和注释
// 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
分配内存,内建函数 new
本质上说跟其他语言中的同名函数功能一样:new(T)
分配了零值填充的 T 类型的内存空间,并且返回其地址,一个 *T 类型的值。用 Go 的术语说,它返回了一个指针,指向新分配的类型 T 的零值。
make
仅适用于 map
,slice
和 channel
,并且返回的不是指针。这三种类型就是引用类型,所以就没有必要返回他们的指针了。因为这三种类型是引用类型,所以必须得初始化。
区别示例代码块
package main import "fmt" type Vertex struct { X, Y float64 } func main() { rect1 := new(Vertex) rect2 := &Vertex{1, 2} fmt.Printf("%v %T %v \n", rect1, rect1, *rect1) fmt.Printf("%v %T %v \n", rect2, rect2, *rect2) rect3 := Vertex{X: 5, Y: 6} fmt.Printf("%v %T\n", rect3, rect3) }
输出结果:
&{0 0} *main.Vertex {0 0} &{1 2} *main.Vertex {1 2} {5 6} main.Vertex
new的作用是初始化一个指向类型的指针(*T),make 的作用是为 slice,map 或 chan 初始化并返回引用(T)。
转载请注明本文标题和链接:《Go语言中new和make的区别》
哟嚯,本文评论功能关闭啦~