What's the difference between make([]int, 0), []int{}, and *new([]int)?

huangapple go评论91阅读模式
英文:

What's the difference between make([]int, 0), []int{}, and *new([]int)?

问题

根据 https://play.golang.org/p/7RPExbwOEU 的内容,它们都打印相同的结果,并且具有相同的长度和容量。在初始化切片的三种方式中是否有区别?是否有首选的方式?我发现自己经常同时使用 make([]int, 0)[]int{}

英文:

According to https://play.golang.org/p/7RPExbwOEU they all print the same and have the same length and capacity. Is there a difference between the three ways to initialize a slice? Is there a preferred way? I find myself using both make([]int, 0) and []int{} with the same frequency.

答案1

得分: 9

这是初始化一个长度为0的切片。

make([]int, 0)

使用make是初始化一个具有与长度不同的特定容量的切片的唯一方法。这将分配一个长度为0但容量为1024的切片。

make([]int, 0, 1024)

这是一个切片字面量,也会初始化一个长度为0的切片。使用这个或者make([]int, 0)完全是个人偏好。

[]int{}

这是初始化一个指向切片的指针,然后立即对其进行解引用。切片本身尚未初始化,仍然为nil,因此实际上什么也没做,等同于[]int(nil)

*new([]int)
英文:

This initializes a 0 length slice.

make([]int, 0)

Using make is the only way to initialize a slice with a specific capacity different than the length. This allocates a slice with 0 length, but a capacity of 1024.

make([]int, 0, 1024)

This is a slice literal, which also initializes a 0 length slice. Using this or make([]int, 0) is solely preference.

[]int{}

This initializes a pointer to a slice, which is immediately dereferenced. The slice itself has not been initialized and will still be nil, so this essentially does nothing, and is equivalent to []int(nil)

*new([]int)

huangapple
  • 本文由 发表于 2017年3月15日 03:55:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/42795382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定