我是靠谱客的博主 老实斑马,这篇文章主要介绍golang中的new和make到底有什么区别?,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
// 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。

一下是各个类型的零值:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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的变量是没法操作的。

复制代码
1
2
3
4
5
6
7
8
9
10
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 常用在需要生成零值的结构体指针变量

复制代码
1
2
p := new(Per)

等价于

复制代码
1
2
p := &Per{}

接下来看一看make

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 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,没法使用,因此还需要进一步赋予合理的值,叫做初始化。

复制代码
1
2
3
4
a := make([]int, 1, 10) b := make(map[string]string) c := make(chan int, 1)

最后

以上就是老实斑马最近收集整理的关于golang中的new和make到底有什么区别?的全部内容,更多相关golang中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(85)

评论列表共有 0 条评论

立即
投稿
返回
顶部