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

最新文章

  1. 在Android中Intent的概念及应用(一)——显示Intent和隐式Intent
  2. Number()、parseInt() 和 parseFloat() 的区别
  3. 黑马程序员——OC语言Foundation框架 (2) NSArray NSSet NSDictionary\NSMutableDictionary
  4. leetcode 93 Restore IP Addresses ----- java
  5. pom.xml报错
  6. textarea限制字符数
  7. 基类方法的反隐藏 反private 秘籍
  8. 在win7与XP系统下 C#缺省路径不同
  9. Python学习 常识+基础基础
  10. 类A是公共的,应在名为A.java的文件中声明错误
  11. 【闲谈】应聘时要问HR的7个问题
  12. Python课程第四天作业
  13. esxi虚拟机克隆后的主机网卡设置
  14. IE8兼容问题
  15. Linux重启服务器步骤
  16. 初始Golang
  17. python3 面向对象编程--类的封装和继承
  18. Java并发编程的艺术(二)——重排序
  19. 【LeetCode】229. Majority Element II
  20. vim 配色(mac)

热门文章

  1. arcgis js 之 渔网工具(调用地图服务)
  2. 【atcoder】Enclosed Points [abc136F]
  3. MySQL开启binlog无法启动ct 10 21:27:31 postfix/pickup[4801]: warning: 6BD991A0039: message has been queue
  4. C和指针--编程题9.14第10小题--判断回文函数
  5. All-in-One Office,不容错过的办公插件
  6. xml树结构
  7. org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException
  8. mysql_config_editor设置
  9. swoole 协程channel乱测
  10. 题解 [BZOJ4886] 叠塔游戏