Go 语言中的 new() 和 make()

Go 语言中的 new() 和 make(),第1张

 博客主页:🏆看看是李XX还是李歘歘 🏆

🌺每天分享一些包括但不限于计算机基础、算法等相关的知识点🌺

💗点关注不迷路,总有一些📖知识点📖是你想要的💗

⛽️今天的内容是   Go 语言中的 new() 和 make()   ⛽️💻💻💻

make和new是GO里面的两个内置函数,用来创建并分配元素的内存。区别是什么?

new 为任意类型【包括:chan、map 以及 slice】分配一片内存空间(allocates memory),并返回指向这片内存的指针。下面的代码可以看出,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

make 只能为 chan、map 以及 slice 的分配内存空间并初始化(allocates and initializes an object of type),从下面的代码可以看出,make接受多个参数,而且它返回的类型就是这三个类型本身,因为这三种类型就是引用类型,所以就没有必要返回他们的指针。

slice:长度即为slice的大小,slice的容量等于它的长度,第三个参数可以指定其容量大小,容量必须大于长度,三个参数,第一个是类型,第二个是slice长度,第三个是slice容量,容量必须大于长度,别问(问就是会报错);slice有len()获取长度,cap()获取容量。

map:空的map会分配足够多的内存空间容纳指定个数的元素(todo怎么保证足够多?),可以分配一个小点的起始大小,只能有两个参数,第一个是类型,第二个是map大小;map只有len()获取长度。

chan:这个channel的初始化缓冲区大小为chan的容量大小,如果为0或者没有传,此channel将没有缓存,也是有两个参数,第一个是类型,第二个是channel缓存区大小;channel有len()获取缓存区元素个数,cap()获取缓冲区容量。

// 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

突然感觉map有种被针对的感觉;

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/996062.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存