当前位置:网站首页>golang - new和make的区别
golang - new和make的区别
2022-06-27 20:47:00 【云闲不收】
许多小伙伴在刚接触 Golang 的时候不理解为什么会有两个用于分配内存的函数: new 和 make,俗话说:存在即合理,下面就来详细说明下这两者的区别。
一、new
先看函数声明:
func new(Type) *Type
new 是 Golang 的内建函数,用于分配内存,其中,第一个参数是类型,返回值是类型的指针,其值被初始化为“零”(类型对应的零值,int 初始化为0,bool初始化为 false 等)。
例如:
package main
import “fmt”
func main() {
id := new(int)
name := new(string)
flag := new(bool)
fmt.Printf(“id type: %T value: %v\n”, id, *id)
fmt.Printf(“name type: %T value: %v\n”, name, *name)
fmt.Printf(“flag type: %T value: %v\n”, flag, *flag)
}
输出:
id type: *int value: 0
name type: *string value:
flag type: *bool value: false
从上述例子可以看到,初始化的“零”值根据类型不同而不同,整数初始化为 0,字符串初始化为空,bool类型初始化为 false。
二、make
先看函数声明:
func make(t Type, size …IntegerType) Type
make 是 Golang 的内建函数,仅用于分配和初始化 slice、map 以及 channel 类型的对象,三种类型都是结构。返回值为类型,而不是指针。
slice 源码结构:
type slice struct {
array unsafe.Pointer //指针
len int //长度
cap int //容量
}
map 源码结构:
// A header for a Go map.
type hmap struct {
// Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go.
// Make sure this stays in sync with the compiler’s definition.
count int // # live cells == size of map. Must be first (used by len() builtin)
flags uint8
B uint8 // log_2 of # of buckets (can hold up to loadFactor * 2^B items)
noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details
hash0 uint32 // hash seed
buckets unsafe.Pointer // array of 2^B Buckets. may be nil if count==0.
oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
nevacuate uintptr // progress counter for evacuation (buckets less than this have been evacuated)
extra *mapextra // optional fields
}
channel 源码结构:
type hchan struct {
qcount uint // total data in the queue
dataqsiz uint // size of the circular queue
buf unsafe.Pointer // points to an array of dataqsiz elements
elemsize uint16
closed uint32
elemtype *_type // element type
sendx uint // send index
recvx uint // receive index
recvq waitq // list of recv waiters
sendq waitq // list of send waiters
// lock protects all fields in hchan, as well as several
// fields in sudogs blocked on this channel.
//
// Do not change another G's status while holding this lock
// (in particular, do not ready a G), as this can deadlock
// with stack shrinking.
lock mutex
}
例如:
package main
import “fmt”
func main() {
//map
fmt.Println(“map:”)
var nameId = make(map[string]int, 0)
fmt.Printf(“nameId \ntype: %#v\n”, nameId)
nameId[“Golang”] = 1
nameId[“C++”] = 2
nameId[“PHP”] = 3
for name, id := range nameId {
fmt.Printf("name = %v, id = %v\n", name, id)
}
// slice
var hobby = make([]string, 2, 100) // 其中 2是长度,100是容量
hobby[0] = "打篮球"
hobby[1] = "乒乓球"
fmt.Println("\nslice:")
fmt.Printf("length = %v caps = %v\n", len(hobby), cap(hobby))
for _, name := range hobby {
fmt.Println(name)
}
// channel
ch := make(chan int, 3)
ch <- 1
ch <- 2
ch <- 8
close(ch)
fmt.Println("\nchannel:")
for val := range ch { // 遍历数据
fmt.Println(val)
}
}
输出:
[[email protected] test]# go run main.go
map:
nameId
type: map[string]int{}
name = Golang, id = 1
name = C++, id = 2
name = PHP, id = 3
slice:
length = 2 caps = 100
打篮球
乒乓球
channel:
1
2
8
[[email protected] test]#
三、new 和 make的区别
new 和 make 都用于分配内存;
new 和 make 都是在堆上分配内存;
new 对指针类型分配内存,返回值是分配类型的指针,new不能直接对 slice 、map、channel 分配内存;
make 仅用于 slice、map和 channel 的初始化,返回值为类型本身,而不是指针;
————————————————
版权声明:本文为CSDN博主「Linux猿」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/nyist_zxp/article/details/111567784

边栏推荐
- 跨系统数据一致性问题解决方案汇总
- 最新云开发微信余额充电器特效小程序源码
- The National University of Singapore 𞓜 uses model free reinforcement learning to evaluate the energy efficiency of the energy efficiency data center
- 6G显卡显存不足出现CUDA Error:out of memory解决办法
- Livox Lidar+海康Camera 基于loam的实时三维重建生成RGB彩色点云
- 网易云“情怀”底牌失守
- The latest cloud development wechat balance charger special effect applet source code
- Livox lidar+ Haikang camera generates color point cloud in real time
- 用pytorch进行CIFAR-10数据集分类
- [electron] 基础学习
猜你喜欢

【蓝桥杯集训100题】scratch数字计算 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第16题

MapReduce初级编程实践

seata

Livox lidar+ Haikang camera generates color point cloud in real time

Service gateway of microservices

“顶流爱豆制造机”携手四个产业资本,做LP

Discuz小鱼游戏风影传说商业GBK+UTF8版模板/DZ游戏网站模板

Liuleifeng, a "good man in Guangzhou" in the first quarter of 2022, has a strong sense of integrity and food safety

"Top stream Aidou manufacturing machine" cooperates with four industrial capitals to become LP

Spark bug practice (including bug:classcastexception; connectexception; NoClassDefFoundError; runtimeException, etc.)
随机推荐
在线JSON转PlainText工具
Classification of cifar-10 dataset with pytorch
This year's examinees are more "desperate" than the college entrance examination
跟着存档教程动手学RNAseq分析(三):使用DESeq2进行计数标准化
个人TREE ALV 模版-加快你的开发
使用同花顺手机炒股安全吗?
Ice cream or snow "high"?
NDSS 2022 接收的列表
官宣!Apache Doris 从 Apache 孵化器毕业,正式成为 Apache 顶级项目!
跟着存档教程动手学RNAseq分析(二)
用pytorch进行CIFAR-10数据集分类
How to use RPA to achieve automatic customer acquisition?
Batch processing - Excel import template 1.1- support multiple sheet pages
What problems should be paid attention to in the serpentine wiring of PCB?
pytorch实现kaggle猫狗识别
webService
批量处理-Excel导入模板1.1-支持多Sheet页
Introduction to quantitative trading
这届考生,报志愿比高考更“拼命”
Spark bug Practice (including bug: classcastexception; connectexception; noclassdeffounderror; runtimeexceptio, etc.)