概述
// 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
new 开辟一块内存,用来存储Type类型的变量,返回指向该地址的指针。
Type可以为所有类型。
给变量赋值零值 zero value of that type。
一下是各个类型的零值:
bool
-> false
numbers
-> 0
string
-> ""
struct
-> 各自key的零值
pointers -> nil
slices -> nil
maps -> nil
channels -> nil
functions -> nil
interfaces -> nil
有些类型的零值是nil,这个又是什么鬼,可以参考阅读 https://blog.csdn.net/raoxiaoya/article/details/108705176
值为nil的变量是没法操作的。
p := new([]int)
fmt.Println(*p == nil)
// true
fmt.Printf("%pn", p)
// 0xc0000044a0
fmt.Println(*p)
// []
(*p)[0] = 1
// panic: runtime error: index out of range [0] with length 0
从这个意义上来讲
p := new([]int)
与 var p *[]int
的区别在于后者是nil pointer。
new 常用在需要生成零值的结构体指针变量
p := new(Per)
等价于
p := &Per{}
接下来看一看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 开辟一块内存,用来存储Type类型的变量,返回此变量。
Type只能是 slice, map, chan。
初始化类型的值 initializes an object of type。因为它们三个的零值是nil,没法使用,因此还需要进一步赋予合理的值,叫做初始化。
a := make([]int, 1, 10)
b := make(map[string]string)
c := make(chan int, 1)
最后
以上就是老实斑马为你收集整理的golang中的new和make到底有什么区别?的全部内容,希望文章能够帮你解决golang中的new和make到底有什么区别?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复