Wan*_* Yi 86 allocation go slice
在Golang,var s []int和之间有什么区别s := make([]int, 0)?
我发现两者都有效,但哪一个更好?
fab*_*ioM 101
简单的声明
var s []int
Run Code Online (Sandbox Code Playgroud)
不分配内存和s指向nil,而
s := make([]int, 0)
Run Code Online (Sandbox Code Playgroud)
分配内存并s指向内存到具有0个元素的切片.
通常,如果您不知道用例的确切大小,则第一个更惯用.
Von*_*onC 86
除了fabriziom的回答之外,您还可以在" Go Slices:usage and internals "中看到更多示例,其中[]int提到了一个用途:
由于slice(
nil)的零值类似于零长度切片,因此您可以声明切片变量,然后在循环中追加它:
// 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
}
Run Code Online (Sandbox Code Playgroud)
这意味着,要附加到切片,您不必首先分配内存:nil切片p int[]足以作为要添加的切片.
Ste*_*nov 14
刚发现有区别。如果你使用
var list []MyObjects
Run Code Online (Sandbox Code Playgroud)
然后你将输出编码为 JSON,你得到null.
list := make([]MyObjects, 0)
Run Code Online (Sandbox Code Playgroud)
结果[]如预期。
更完整一点(在 中还有一个论点make)示例:
slice := make([]int, 2, 5)
fmt.Printf("length: %d - capacity %d - content: %d", len(slice), cap(slice), slice)
Run Code Online (Sandbox Code Playgroud)
出去:
length: 2 - capacity 5 - content: [0 0]
Run Code Online (Sandbox Code Playgroud)
或者使用动态类型slice:
slice := make([]interface{}, 2, 5)
fmt.Printf("length: %d - capacity %d - content: %d", len(slice), cap(slice), slice)
Run Code Online (Sandbox Code Playgroud)
出去:
length: 2 - capacity 5 - content: [<nil> <nil>]
Run Code Online (Sandbox Code Playgroud)