golang 中 new 和 make 的区别
源码
new和make的源码,对应路径为: $GOPATH/go/src/builtin/builtin.go
// 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 // 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 只需要传入类型即可,make 多了 第二个参数(为 int 类型)
返回值类型不一样。new 返回的为该类型的指针,make 返回的是已实例化的该类型(引用)
实例:
func main() { xiaojia := new([]LAOJIA) fmt.Printf("%T, %v, %p\n", xiaojia, xiaojia, xiaojia) laojia := make([]LAOJIA, 2, 3) fmt.Printf("%T, %v, %p", laojia, laojia, laojia) }
运行结果
*[]main.LAOJIA, &[], 0xc000004078 []main.LAOJIA, [{0 0} {0 0}], 0xc00005a060
小结:
make 和 new 都是 golang 用来分配内存的內建函数,且在堆上分配内存,make 即分配内存,也初始化内存(初始化成零值)。new 只是开辟一个类型宽度的内存,并返回内存地址,但没有初始化内存。
make 返回的还是引用类型(可以说是一个实例);而 new 返回的是指向类型的 指针。
make 只能用来分配及初始化类型为 slice,map,channel 的数据;new 可以分配任意类型的数据。
参考:
golang中new和make的区别: https://zhuanlan.zhihu.com/p/340988277
Go make 和 new 的区别:https://juejin.cn/post/6859145664316571661
共 0 条评论