英文:
How should I define an empty slice in Go?
问题
以下是要翻译的内容:
更准确地说,我似乎可以做这三件事中的任何一件。它们之间有什么区别吗?哪个是最好的,为什么?
var foo []int
foo := []int{}
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?
var foo []int
foo := []int{}
foo := make([]int, 0)
答案1
得分: 9
区别如下:
(1)变量初始化为切片的零值,即nil(foo == nil
)。
(2)和(3)将非nil的切片赋值给变量(foo != nil
)。切片的底层数组指针被设置为保留给0字节分配的地址。
以下几点对于这三个语句都成立:
- 切片的长度为零:
len(foo) == 0
。 - 切片的容量为零:
cap(foo) == 0
。 - 语句不会分配内存。
因为len、cap和append可以处理nil切片,所以(1)通常可以与(2)和(3)互换使用。
语句2和3是短变量声明。这些语句也可以写成带有初始化器的变量声明。
var foo = []int{}
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.
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.
var foo = []int{}
var foo = make([]int, 0)
All of the options are used commonly in Go code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论