如何使用动态 size/length/capacity 制作切片

How to make slice with dynamic size/length/capacity

我似乎可以使用 size/capacity/length/whatever 创建动态切片:

cleaned := []interface{}{}

我怎样才能对 make() 做同样的事情?我试过这个:

cleaned := make([]interface{})

但它要我包括一个长度?

Missing len argument to make

你有两种方法:

  1. 使用 cleaned := make([]interface{},0) 然后调用 cleaned = append(cleaned, your_data)
  2. 正在声明一个空数组:var cleaned []interface{}{}
cleaned := []interface{}{}

how can I do the same with make()?


例如,

package main

import (
    "fmt"
)

func main() {
    {
        cleaned := []interface{}{}
        fmt.Println(len(cleaned), cap(cleaned), cleaned)
    }

    // OR

    {
        cleaned := make([]interface{}, 0)
        fmt.Println(len(cleaned), cap(cleaned), cleaned)
    }

    // OR

    {
        cleaned := make([]interface{}, 0, 0)
        fmt.Println(len(cleaned), cap(cleaned), cleaned)
    }
}

游乐场:https://play.golang.org/p/qndsxIKWjEp

输出:

0 0 []
0 0 []
0 0 []

参考:

The Go Programming Language Specification : Making slices, maps and channe



Comment: jetbrains complains and says Empty slice declaration via literal and suggests replacing with var cleaned []interface{} , but it's unclear why? – Olegzandr Denman


这是一个不同的问题。原因很清楚。

Go Code Review Comments : Declaring Empty Slices

When declaring an empty slice, prefer

var t []string

over

t := []string{}

The former declares a nil slice value, while the latter is non-nil but zero-length. They are functionally equivalent—their len and cap are both zero—but the nil slice is the preferred style.

. . .

例如,

package main

import (
    "fmt"
)

func main() {
    {
        cleaned := []interface{}{}
        fmt.Println(len(cleaned), cap(cleaned), cleaned, cleaned == nil)
    }

    // OR

    {
        cleaned := make([]interface{}, 0)
        fmt.Println(len(cleaned), cap(cleaned), cleaned, cleaned == nil)
    }

    // OR

    {
        cleaned := make([]interface{}, 0, 0)
        fmt.Println(len(cleaned), cap(cleaned), cleaned, cleaned == nil)
    }

    // OR

    {
        var cleaned []interface{}
        fmt.Println(len(cleaned), cap(cleaned), cleaned, cleaned == nil)
    }
}

游乐场:https://play.golang.org/p/9cZOOS2F9qI

输出:

0 0 [] false
0 0 [] false
0 0 [] false
0 0 [] true