当前位置:网站首页>Golang - the difference between new and make
Golang - the difference between new and make
2022-06-27 23:24:00 【Cloud idle】
A lot of little friends just came into contact with Golang I don't understand why there are two functions to allocate memory : new and make, It is said that : Existence is reason , Let's explain the difference between the two in detail .
One 、new
Let's look at the function declaration first :
func new(Type) *Type
new yes Golang Is a built-in function of , Used to allocate memory , among , The first parameter is the type , The return value is a pointer to the type , Its value is initialized to “ zero ”( The zero value corresponding to the type ,int Initialize to 0,bool Initialize to false etc. ).
for example :
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)
}
Output :
id type: *int value: 0
name type: *string value:
flag type: *bool value: false
As can be seen from the above examples , The initialization of the “ zero ” Values vary by type , The integer is initialized to 0, Null string initialization ,bool The type is initialized to false.
Two 、make
Let's look at the function declaration first :
func make(t Type, size …IntegerType) Type
make yes Golang Is a built-in function of , For allocation and initialization only slice、map as well as channel Object of type , All three types are structures . The return type is , Instead of Pointers .
slice Source structure :
type slice struct {
array unsafe.Pointer // The pointer
len int // length
cap int // Capacity
}
map Source structure :
// 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 Source structure :
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
}
for example :
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) // among 2 It's length. ,100 It's capacity
hobby[0] = " To play basketball "
hobby[1] = " Table Tennis "
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 { // Traversal data
fmt.Println(val)
}
}
Output :
[[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
To play basketball
Table Tennis
channel:
1
2
8
[[email protected] test]#
3、 ... and 、new and make The difference between
new and make Are used to allocate memory ;
new and make It's all about allocating memory on the heap ;
new Allocate memory for pointer types , The return value is a pointer to the allocation type ,new Not directly slice 、map、channel Allocate memory ;
make Only used for slice、map and channel The initialization , The return value is the type itself , Instead of Pointers ;
————————————————
Copyright notice : This paper is about CSDN Blogger 「Linux The ape 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/nyist_zxp/article/details/111567784

边栏推荐
- Consumer finance app user insight in the first quarter of 2022 - a total of 44.79 million people
- Web Worker介绍及使用案例
- 2022年PMP项目管理考试敏捷知识点(3)
- PE buys a underwear company
- Open source of local run / development library of hiplot online drawing tool
- 跟着存档教程动手学RNAseq分析(二)
- Small chip chiplet Technology
- [electron] basic learning
- Arcgis-engine二次开发之空间关系查询与按图形查询
- Is it safe to use flush mobile phones to speculate in stocks?
猜你喜欢

消除el-image图片周围间隙

MapReduce初级编程实践

Small chip chiplet Technology

2022年第一季度“广州好人”刘磊峰:具有强烈的诚信意识和食品安全意识

Working at home is more tiring than going to work at the company?

第一性原理(最优解理论)

Spatial relation query and graph based query in secondary development of ArcGIS Engine

Redis principle - string

未能加载文件或程序集“CefSharp.Core.Runtime.dll”或它的某一个依赖项。 不是有效的 Win32 应用程序。 (异常来自 HRESULT:0x800700C1)

Senior headhunting team manager: interviewed 3000 consultants, summarized and organized 8 commonalities (Mao Sheng)
随机推荐
移动端避免使用100vh[通俗易懂]
Livox Lidar+APX15 实时高精度雷达建图复现整理
本机部署一个MongoDB单节点服务器,并启用auth验证、开启oplog
[网络]常见的请求方法
跟着存档教程动手学RNAseq分析(四):使用DESeq2进行DE分析的QC方法
华为伙伴暨开发者大会2022 | 麒麟软件携手华为共建计算产业,共创数智未来
量化交易入门教程
个人TREE ALV 模版-加快你的开发
通过tidymodels使用XGBOOST
Azure Kinect DK realizes 3D reconstruction (Jetson real-time version)
Using xgboost with tidymodels
Summary of solutions to cross system data consistency problems
OData - SAP S4 OP 中使用SAP API Hub 的API
「R」使用ggpolar绘制生存关联网络图
golang - new和make的区别
The latest cloud development wechat balance charger special effect applet source code
Feign implements path escape through custom annotations
Personal tree ALV template - accelerate your development
在线JSON转PlainText工具
用pytorch进行CIFAR-10数据集分类