在golang中,make和new都是分配内存的,但是它们之间还是有些区别的,只有理解了它们之间的不同,才能在合适的场合使用。

简单来说,new只是分配内存,不初始化内存; 而make即分配又初始化内存。所谓的初始化就是给类型赋初值,比如字符为空,整型为0, 逻辑值为false等。

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

可以看出,它的参数是一个类型,返回值为指向该类型内存地址的指针,同时会把分配的内存置为零,也就是类型的零值, 即字符为空,整型为0, 逻辑值为false

看几个new的示例

   type P struct{
Name string
Age int
}
var a *[2]int
var s *string
var b *bool
var i *int
var ps *P a = new([2]int)
s = new(string)
b = new(bool)
i = new(int)
ps = new(P) //结构 fmt.Println(a, " ", *a)
fmt.Println(s, " ",*s)
fmt.Println(b, " ",*b)
fmt.Println(i, " ",*i)
fmt.Println(ps, " ", *ps)

输出结果如下

&[0 0]   [0 0]
0xc00000e1e0
0xc00001a07a false
0xc00001a090 0
&{ 0} { 0}

上面示例是基本的类型,再看下slice, map,chan这些用new咋操作

    map操作
var mp *map[string]string
mp = new(map[string]string)
//*mp = make(map[string]string) //这行注掉会panic "panic: assignment to entry in nil map""
(*mp)["name"] = "lc"
fmt.Println((*mp)["name"]) slice操作
var ms *[]string
ms = new([]string)
//*ms = make([]string,5) //这行注掉会pance "panic: runtime error: index out of range"
(*ms)[0] = "lc"
fmt.Println((*ms)[0])

上面可以看出,silce、map、channel等类型属于引用类型,引用类型初始化为nil,nil是不能直接赋值的,也不能用new分配内存,还需要使用make来分配。

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,channel等初始化内存,它们返回的就是引用类型,那么就没必要返回指针了

看下make的一些示例

    mm :=make(map[string]string)
mm["name"] = "lc"
fmt.Println(mm["name"]) mss :=make([]int,2)
mss[0] = 100
fmt.Println(mss[0]) ch :=make(chan int,1)
ch <-100 fmt.Println(<-ch)

小结

make 仅用来分配及初始化类型为 slice、map、chan 的数据。new 可分配任意类型的数据.

new 分配返回的是指针,即类型 *Type。make 返回引用,即 Type.

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

golang中,new和make的区别的更多相关文章

  1. 【GoLang】GoLang 中 make 与 new的区别

    make.new操作 make用于内建类型(map.slice 和channel)的内存分配.new用于各种类型的内存分配. 内建函数new本质上说跟其它语言中的同名函数功能一样:new(T)分配了零 ...

  2. golang中数组与切片的区别

    初始化:数组需要指定大小,不指定也会根据初始化的自动推算出大小,不可改变 数组: a := [...],,} a := [],,} 切片: a:= [],,} a := make([]) a := m ...

  3. golang 中Pointers Vs References

    原文: https://spf13.com/post/go-pointers-vs-references/ Pointers Vs References Some languages includin ...

  4. golang中new和make区别

    golang 中有两个内存分配机制 :new和make,二者有明显区别. new:用来初始化一个对象,并且返回该对象的首地址.其自身是一个指针.可用于初始化任何类型 make:返回一个初始化的实例,返 ...

  5. golang中sync.RWMutex和sync.Mutex区别

    golang中sync包实现了两种锁Mutex (互斥锁)和RWMutex(读写锁),其中RWMutex是基于Mutex实现的,只读锁的实现使用类似引用计数器的功能. type Mutex     f ...

  6. golang中数组指针与指针数组的区别实现

      指针数组和数组的指针,指的是两个不同的东西. 指针数组是有指针组成的数组,数组的指针是一个数组的指针. package main import "fmt" const MAX ...

  7. 【GoLang】golang 中 defer 参数的蹊跷

    参考资料: http://studygolang.com/articles/7994--Defer函数调用参数的求值 golang的闭包和普通函数调用区别:http://studygolang.com ...

  8. 说说不知道的Golang中参数传递

    本文由云+社区发表 导言 几乎每一个C++开发人员,都被面试过有关于函数参数是值传递还是引用传递的问题,其实不止于C++,任何一个语言中,我们都需要关心函数在参数传递时的行为.在golang中存在着m ...

  9. Go实战--golang中使用JWT(JSON Web Token)

    http://blog.csdn.net/wangshubo1989/article/details/74529333 之前写过关于golang中如何使用cookie的博客: 实战–go中使用cook ...

随机推荐

  1. vue-cli项目中引入第三方插件

    前言 最近有小伙伴问道如何在vue-cli项目中引入第三方插件或者库,例如如果想在项目中使用jQuery中的Ajax请求数据呢?或者我想使用Bootstrap框架呢?等等这些问题,本篇博客将带你学习如 ...

  2. 一些实用的 Laravel 小技巧

    Laravel 中一些常用的小技巧,说不定你就用上了. 1.侧栏 网站一般都有侧栏,用来显示分类,标签,热门文章,热门评论啥的,但是这些侧栏都是相对独立的模块,如果在每一个引入侧栏的视图中都单独导入与 ...

  3. WPF特点

    前言:为什么要学习WPF呢?因为随着现阶段硬件技术的升级以及客户对体验的要求越来越高,传统的GDI和USERS(或者是GDI+.USERS)已经不能满足这个需求,因此,WPF技术应运而生. WPF的特 ...

  4. Android 菜单 Menu

    @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to th ...

  5. 重启docker服务应用,自启停命令.

    #重启docker服务应用,不自动开启docker容器 docker update --restart=no (docker容器CONTAINER ID 或 docekr容器NAMES) #重启doc ...

  6. 集合系列 Map(十三):LinkedHashMap

    我们之前说过 LinkedHashMap 是在 HashMap 的基础上,增加了对插入元素的链表维护.那么其到底是怎么实现的呢?今天这篇文章就带我们来一探究竟. public class Linked ...

  7. oc:定时删除ES日志数据释放空间

    修改方法: 1.直接编辑修改 查看当前logging-curator配置,了解当前定时删除大的策略. oc edit configmap/logging-curator 打开后,可以直接编辑保存. 2 ...

  8. 几种设计良好结构以提高.NET应用性能的方法

    写在前面 设计良好的系统,除了架构层面的优良设计外,剩下的大部分就在于如何设计良好的代码,.NET提供了很多的类型,这些类型非常灵活,也非常好用,比如List,Dictionary.HashSet.S ...

  9. MySQL实现统计数据并插入数据的存储过程

    统计存储过程,这里是将统计的结果插入一个表中,后台可以有定时任务来调此存储过程.以下业务是统计仓库中商品流转情况,包括:日期.商品总数.入库数量.出库数量. BEGIN DECLARE ES_COR_ ...

  10. 从0系统学Android--3.2四种基本布局

    从0系统学Android--3.2四种基本布局 本系列文章目录:更多精品文章分类 本系列持续更新中.... 3.3 系统控件不够用?创建自定义控件 上一节我们学习了 Android 中的一些常用的控件 ...