详解Go语言中new和make关键字的区别

作者:yongxinz 时间:2024-05-21 10:19:20 

本篇文章来介绍一道非常常见的面试题,到底有多常见呢?可能很多面试的开场白就是由此开始的。那就是 new 和 make 这两个内置函数的区别。

其实这个问题本身并不复杂,简单来说就是,new 只分配内存,而 make 只能用于 slice、map 和 chan 的初始化,下面我们就来详细介绍一下。

new

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 函数为变量分配内存空间:

p1 := new(int)
fmt.Printf("p1 --> %#v \n ", p1) //(*int)(0xc42000e250) 
fmt.Printf("p1 point to --> %#v \n ", *p1) //0

var p2 *int
i := 0
p2 = &i
fmt.Printf("p2 --> %#v \n ", p2) //(*int)(0xc42000e278) 
fmt.Printf("p2 point to --> %#v \n ", *p2) //0

上面的代码是等价的,new(int) 将分配的空间初始化为 int 的零值,也就是 0,并返回 int 的指针,这和直接声明指针并初始化的效果是相同的。

当然,new 函数不仅能够为系统默认的数据类型分配空间,自定义类型也可以使用 new 函数来分配空间,如下所示:

type Student struct {
   name string
   age int
}
var s *Student
s = new(Student) //分配空间
s.name = "zhangsan"
fmt.Println(s)

这就是 new 函数,它返回的永远是类型的指针,指针指向分配类型的内存地址。需要注意的是,new 函数只会分配内存空间,但并不会初始化该内存空间。

make

make 也是用于内存分配的,但是和 new 不同,它只用于 slice、map 和 chan 的内存创建,而且它返回的类型就是这三个类型本身,而不是他们的指针类型。因为这三种类型本身就是引用类型,所以就没有必要返回他们的指针了。

其函数签名如下:

源码

// 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, so make([]int, 0, 10) allocates a slice of length 0 and
// capacity 10.
// 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 函数的 t 参数必须是 slice、map 和 chan 中的一个,并且返回值也是类型本身。

使用

下面用 slice 来举一个例子:

var s1 []int
if s1 == nil {
    fmt.Printf("s1 is nil --> %#v \n ", s1) // []int(nil)
}

s2 := make([]int, 3)
if s2 == nil {
    fmt.Printf("s2 is nil --> %#v \n ", s2)
} else {
    fmt.Printf("s2 is not nill --> %#v \n ", s2)// []int{0, 0, 0}
}

slice 的零值是 nil,但使用 make 初始化之后,slice 内容被类型 int 的零值填充,如:[]int{0, 0, 0}

map 和 chan 也是类似的,就不多说了。

  • make 只能用来分配及初始化类型为 slice、map 和 chan 的数据。new 可以分配任意类型的数据;

  • new 分配返回的是指针,即类型 *Type。make 返回类型本身,即 Type

  • new 分配的空间被清零。make 分配空间后,会进行初始化;

来源:https://mp.weixin.qq.com/s/NBDkI3roHgNgW1iW4e_6cA

标签:Go语言,new,make
0
投稿

猜你喜欢

  • 实例解析MySQL中的存储过程及存储过程的调用方法

    2024-01-21 19:45:04
  • Python Pandas高级教程之时间处理

    2021-08-12 14:04:49
  • MySQL Left JOIN时指定NULL列返回特定值详解

    2024-01-16 09:55:32
  • 简单方法实现网页自动适应任何分辨率任何窗口大小

    2008-09-13 19:28:00
  • 基于python+selenium自动健康打卡的实现代码

    2022-04-28 06:31:28
  • python绘制地震散点图

    2021-12-21 13:09:08
  • 用Pygal绘制直方图代码示例

    2023-12-15 22:41:01
  • MySQL内建复制功能来优化可用性

    2010-10-25 20:20:00
  • asp数据转换函数示例

    2008-04-13 06:52:00
  • 如何给MD5加上salt随机盐值

    2022-01-13 05:32:37
  • 连接MySQL时出现1449与1045异常解决办法

    2024-01-16 14:07:02
  • ThinkPHP中URL路径访问与模块控制器之间的关系

    2024-05-05 09:16:40
  • Python Numpy学习之索引及切片的使用方法

    2021-09-04 02:59:01
  • 利用python判断字母大小写的几种方法小结

    2022-05-10 16:41:49
  • python中的逆序遍历实例

    2023-02-27 19:57:45
  • 基于tensorflow权重文件的解读

    2023-11-04 02:05:35
  • MySQL插入时间差八小时问题的解决方法

    2024-01-28 22:00:09
  • Go语言实现的简单网络端口扫描方法

    2024-04-26 17:23:06
  • Python 使用 Pillow 模块给图片添加文字水印的方法

    2022-06-13 04:13:37
  • matplotlib绘制符合论文要求的图片实例(必看篇)

    2023-08-12 08:08:39
  • asp之家 网络编程 m.aspxhome.com