声明切片还是制作切片? [英] 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?
推荐答案
除了 fabriziom 的 答案,您可以在Go Slices: usage and internals",其中提到了 []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:
由于切片的零值 (nil
) 的作用类似于零长度切片,您可以声明一个切片变量,然后在循环中附加到它:
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
}
这意味着,要附加到切片,您不必先分配内存:nil
切片 p int[]
作为一个切片就足够了添加到.
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.
这篇关于声明切片还是制作切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!