首页 > 编程语言 > 详细

Go语言中new和make的使用与区别

时间:2020-04-14 12:24:03      阅读:48      评论:0      收藏:0      [点我收藏+]

1.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

 示例代码:

a := new(int)	     //申请指定类型的一块空间,并且返回一个指向该类型内存地址的指针
fmt.Println(*a)		//同时会把分配的内存地址的变量值置为类型的零值,此处结果为0
*a = 1			//对该指针对应的值赋值
fmt.Println(*a)		//结果为1

 总结: 它只接受一个参数,这个参数是一个类型,分配好内存后,返回一个指向该类型内存地址的指针。同时会把分配的内存地址的变量值置为类型的零值

2.make方法

源码中的make方法

func make(t Type, size ...IntegerType) Type

示例代码

arr := make([]int, 10)  //创建切片
fmt.Println(arr)       //[0 0 0 0 0 0 0 0 0 0]
fmt.Printf("%T\n", arr)  //[]int
fmt.Printf("%p\n", arr)  //内存地址  0xc00001e0a0

make也是用于内存分配的,但是和new不同,它只用于chan、map以及切片的内存创建,而且它返回的类型就是这三个类型本身,

而不是他们的指针类型,因为这三种类型就是引用类型,所以就没有必要返回他们的指针了

一句话来说明:

make返回的还是这三个引用类型本身;而new返回的是指向类型的指针。

Go语言中new和make的使用与区别

原文:https://www.cnblogs.com/weisunblog/p/12696763.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!