How should I define an empty slice in Go?

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

How should I define an empty slice in Go?

问题

以下是要翻译的内容:

更准确地说,我似乎可以做这三件事中的任何一件。它们之间有什么区别吗?哪个是最好的,为什么?

  1. var foo []int
  2. foo := []int{}
  3. foo := make([]int, 0)

请注意,我只会返回翻译好的部分,不会回答关于翻译的问题。

英文:

Or more precisely, it seems like I could do any of these three things. Is there any difference between them? Which is the best and why?

  1. var foo []int
  2. foo := []int{}
  3. foo := make([]int, 0)

答案1

得分: 9

区别如下:

(1)变量初始化为切片的零值,即nil(foo == nil)。

(2)和(3)将非nil的切片赋值给变量(foo != nil)。切片的底层数组指针被设置为保留给0字节分配的地址。

以下几点对于这三个语句都成立:

  • 切片的长度为零:len(foo) == 0
  • 切片的容量为零:cap(foo) == 0
  • 语句不会分配内存。

Playground示例

因为lencapappend可以处理nil切片,所以(1)通常可以与(2)和(3)互换使用。

语句2和3是短变量声明。这些语句也可以写成带有初始化器的变量声明。

  1. var foo = []int{}
  2. var foo = make([]int, 0)

所有这些选项在Go代码中都常见使用。

英文:

The difference is:

(1) The variable is initialized to the zero value for a slice, which is nil (foo == nil).

(2) and (3) assign non-nil slices to the variable (foo != nil). The slice's underlying array pointer is set to an address reserved for 0-byte allocations.

The following points are true for all three statements:

  • The slice length is zero: len(foo) == 0.
  • The slice capacity is zero: cap(foo) == 0.
  • The statement does not allocate memory.

Playground example

Because len, cap and append work with nil slices, (1) can often be used interchangeably with (2) and (3).

Statements 2 and 3 are short variable declarations. These statements can also be written as a variable declaration with an initializer.

  1. var foo = []int{}
  2. var foo = make([]int, 0)

All of the options are used commonly in Go code.

huangapple
  • 本文由 发表于 2015年1月21日 02:47:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/28052933.html
匿名

发表评论

匿名网友

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

确定