Go语言中new和make的区别
2024-09-08 09:56:55
Go语言中new跟make是内置函数,主要用来创建分配类型内存。
new( )
new(T)创建一个没有任何数据的类型为T的实例,并返回该实例的指针;
源码解析
func new
func new(Type) *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.
make( )
make(T, args)只能创建 slice、map和channel,并且返回一个有初始值args(非零)的T类型的实例,非指针。
源码解析
func make
func make(Type, size IntegerType) Type
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.
二者异同
二者都是内存的分配(堆上),但是make
只用于slice、map以及channel的初始化(非零值);而new
用于类型的内存分配,并且内存置为零。所以在我们编写程序的时候,就可以根据自己的需要很好的选择了。
make
返回的还是这三个引用类型本身;而new
返回的是指向类型的指针。
作者:子恒|haley
出处:http://www.haleyl.com
交流沟通:QQ群866437035
最新文章
- 在Android中Intent的概念及应用(一)——显示Intent和隐式Intent
- Number()、parseInt() 和 parseFloat() 的区别
- 黑马程序员——OC语言Foundation框架 (2) NSArray NSSet NSDictionary\NSMutableDictionary
- leetcode 93 Restore IP Addresses ----- java
- pom.xml报错
- textarea限制字符数
- 基类方法的反隐藏 反private 秘籍
- 在win7与XP系统下 C#缺省路径不同
- Python学习 常识+基础基础
- 类A是公共的,应在名为A.java的文件中声明错误
- 【闲谈】应聘时要问HR的7个问题
- Python课程第四天作业
- esxi虚拟机克隆后的主机网卡设置
- IE8兼容问题
- Linux重启服务器步骤
- 初始Golang
- python3 面向对象编程--类的封装和继承
- Java并发编程的艺术(二)——重排序
- 【LeetCode】229. Majority Element II
- vim 配色(mac)
热门文章
- arcgis js 之 渔网工具(调用地图服务)
- 【atcoder】Enclosed Points [abc136F]
- MySQL开启binlog无法启动ct 10 21:27:31 postfix/pickup[4801]: warning: 6BD991A0039: message has been queue
- C和指针--编程题9.14第10小题--判断回文函数
- All-in-One Office,不容错过的办公插件
- xml树结构
- org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException
- mysql_config_editor设置
- swoole 协程channel乱测
- 题解 [BZOJ4886] 叠塔游戏