英文:
Declare slice or make slice?
问题
在Go语言中,var s []int
和s := make([]int, 0)
有什么区别?
我发现这两种方式都可以工作,但哪一种更好?
英文:
In Go, what is the difference between var s []int
and s := make([]int, 0)
?
I find that both works, but which one is better?
答案1
得分: 160
简单声明
var s []int
不分配内存,s
指向 nil
,而
s := make([]int, 0)
分配内存,s
指向一个包含 0 个元素的切片。
通常情况下,如果你不知道你的用例的确切大小,第一种方式更符合惯用法。
英文:
Simple declaration
var s []int
does not allocate memory and s
points to nil
, while
s := make([]int, 0)
allocates memory and s
points to memory to a slice with 0 elements.
Usually, the first one is more idiomatic if you don't know the exact size of your use case.
答案2
得分: 111
除了fabriziom的答案之外,你还可以在“Go Slices: usage and internals”中看到更多的示例,其中提到了[]int
的用法:
由于切片的零值(
nil
)就像一个零长度的切片,你可以声明一个切片变量,然后在循环中向其追加:
// Filter返回一个只包含满足f()条件的元素的新切片
func Filter(s []int, fn func(int) bool) []int {
var p []int // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
这意味着,要向切片追加元素,你不必先分配内存:nil
切片p int[]
就足够作为一个切片来添加元素。
英文:
In addition to fabriziom's answer, you can see more examples at "Go Slices: usage and internals", where a use for []int
is mentioned:
> Since the zero value of a slice (nil
) acts like a zero-length slice, you can declare a slice variable and then append to it in a loop:
// Filter returns a new slice holding only
// the elements of s that satisfy f()
func Filter(s []int, fn func(int) bool) []int {
var p []int // == nil
for _, v := range s {
if fn(v) {
p = append(p, v)
}
}
return p
}
It means that, to append to a slice, you don't have to allocate memory first: the nil
slice p int[]
is enough as a slice to add to.
答案3
得分: 23
刚刚发现了一个区别。如果你使用以下代码:
var list []MyObjects
然后将输出编码为 JSON,你会得到 null
。
而使用以下代码:
list := make([]MyObjects, 0)
会得到预期的 []
。
英文:
Just found a difference. If you use
var list []MyObjects
and then you encode the output as JSON, you get null
.
list := make([]MyObjects, 0)
results in []
as expected.
答案4
得分: 8
一个稍微完整一点的例子(在.make()
中有一个额外的参数):
slice := make([]int, 2, 5)
fmt.Printf("长度:%d - 容量:%d - 内容:%d", len(slice), cap(slice), slice)
输出:
长度:2 - 容量:5 - 内容:[0 0]
或者使用动态类型的slice
:
slice := make([]interface{}, 2, 5)
fmt.Printf("长度:%d - 容量:%d - 内容:%d", len(slice), cap(slice), slice)
输出:
长度:2 - 容量:5 - 内容:[<nil> <nil>]
英文:
A bit more complete example (one more argument in .make()
):
slice := make([]int, 2, 5)
fmt.Printf("length: %d - capacity %d - content: %d", len(slice), cap(slice), slice)
Out:
length: 2 - capacity 5 - content: [0 0]
Or with a dynamic type of slice
:
slice := make([]interface{}, 2, 5)
fmt.Printf("length: %d - capacity %d - content: %d", len(slice), cap(slice), slice)
Out:
length: 2 - capacity 5 - content: [<nil> <nil>]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论