在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. Caffe源码-Net类(上)

    Net类简介 Net类主要处理各个Layer之间的输入输出数据和参数数据共享等的关系.由于Net类的代码较多,本次主要介绍网络初始化部分的代码.Net类在初始化的时候将各个Layer的输出blob都统 ...

  2. 【1封新邀请】想跟谷歌、七牛、kyligence等大佬面对面的交流吗?

    2020年1月4日-5日,"ECUG Con 2020"大会将于杭州举行.本次大会以"ECUG For Future"为主题,围绕五大技术主题,邀请到来自七牛云 ...

  3. WC集训DAY2笔记 组合计数 part.1

    目录 WC集训DAY2笔记 组合计数 part.1 基础知识 组合恒等式 错排数 卡特兰数 斯特林数 伯努利数 贝尔数 调和级数 后记 补完了几天前写的东西 WC集训DAY2笔记 组合计数 part. ...

  4. [JZOJ A组]球 题解

    球(ball) [问题描述] 小 T 有 n 个桶和 2n − 1 个球,其中第 i 个桶能装前 2i − 1 个球.每个桶只能装一个球. 现在小 T 取了 m 个桶和 m 个球,并将这些球各自放在 ...

  5. 4. abp中的asp.net core模块剖析

    相关模块 AbpAspNetCoreModule AbpAspNetCoreMvcModule AbpAspNetCoreMvcContractsModule abp通过这三个模块加载并配置了 asp ...

  6. 【代码审计】ESPCMSP8(易思企业建站管理系统)漏洞报告

    0x00简介 项目名称:ESPCMS-P8(易思企业建站管理系统) 测试平台:Windwos 版本信息:P8.19082801稳定版 更新时间:2019-08-30 00:56:32 网站官网:htt ...

  7. IO测试工具 - 用于IO测试 ; linux benchmarks

    IO测试工具,用于磁盘IO测试,下面进行使用列表进行记录: iozone fio dd ioping iotop iostat bonnie++ crystalDisk Atto as-ssd-ben ...

  8. Linux 删除特殊字符文件名或目录

    通过文件的inode号删除文件 先用ls -i 找出要删除文件的inode 号 ls -i |grep xxxxxx|awk '{print $2}'|xargs -i rm -f {} xxxxxx ...

  9. 【linux命令】软连接和硬链接的区别(ln命令)

    Linux 文件系统把硬盘分为三个部分:超级块.inode 列表.数据区 inode 指示:该文件的数据存放在数据区的哪些块内.因为这个“映射”关系不能变更,因此,inode 相当于代表着文件本身.( ...

  10. SpringAOP基础

    例1.已知有这么一段代码,会打印出Hello public static void main(String[] args) { sayHello(); } public static void say ...