golang 面试一:make和new的区别

本文详细解析了Go语言中new和make两个内建函数的区别。new分配内存并返回类型零值的指针,而make则针对slice、map和chan进行初始化,返回直接引用。new后的操作需要额外指针,make则直接返回可使用的结构。在使用时,new适用于基本类型和结构体,make则在需要初始化的数据结构中更为常见。
摘要由CSDN通过智能技术生成

golang 面试一:make和new的区别

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分配返回的是引用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值