申报片或制作片? [英] Declare slice or make slice?
问题描述
在Golang中, var s [] int
和 s:= make([] int,0)$ < C $ C>?
In Golang, what is the difference between var s []int
and s := make([]int, 0)
?
我发现这两种方法都有效,但哪一种更好?
I find that both works, but which one is better?
推荐答案
<除了 fabriziom 的 answer ,您可以在 Go Slices:usage和内部函数,其中提到了 [] 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屋!