美文网首页go学习
golang : new make difference

golang : new make difference

作者: dncmn | 来源:发表于2017-12-23 12:10 被阅读0次

golang中new和make的区别

不同:

1、初始化对象不同

new:array和struct

make:map、channel、slice

2、返回值类型不同

new:返回一个指向参数的一个指针,并且初始化的那个值用zero value初始化

make:返回要给与参数类型一样的类型,并且初始化

slice:至少指定一个参数

map:没有必要制定,这个起始的大小是可以忽略的

channel:制定是否是缓冲通道。

slice:

大小指定了长度,切片的容量等于它的长度,第二个整数可能制定不同的容量,

这个值一定小于这个切片的长度。

make([]int,5)  length=5  cap=5

make([]int,0,5) length=0 cap=5

map:

一个空的map被分配足够大的空间来容纳制定数量的元素,在这种情况下,分配一个启始这个大小的数字就可以忽略,

channel:

make(channel int,8) 缓冲通道

make(channel int) 非缓冲通道

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.

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, so make([]int, 0, 10) allocates a slice of length 0 and

// capacity 10.

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

相关文章

网友评论

    本文标题:golang : new make difference

    本文链接:https://www.haomeiwen.com/subject/ppafgxtx.html