如何制作具有动态大小/长度/容量的切片

我似乎能够使用以下命令创建一个具有动态大小/容量/长度/任何内容的切片:

cleaned := []interface{}{}

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

cleaned := make([]interface{})

但它想要我包括一个长度?

缺少 len 参数


MYYA
浏览 135回答 2
2回答

ibeautiful

你有两种方法:使用cleaned := make([]interface{},0)and 调用cleaned = append(cleaned, your_data)声明一个空数组:var cleaned []interface{}{}

Cats萌萌

cleaned := []interface{}{}我怎样才能用 make() 做同样的事情?例如,package mainimport (    "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 []声明空切片时,更喜欢var t []string超过t := []string{}前者声明一个 nil 切片值,而后者非 nil 但长度为零。它们在功能上是等效的——它们的 len 和 cap 都为零——但 nil 切片是首选样式。. . .例如,package mainimport (    "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 [] false0 0 [] false0 0 [] false0 0 [] true
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go