初始化空切片的正确方法 [英] Correct way to initialize empty slice

查看:32
本文介绍了初始化空切片的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要声明一个空切片,大小不固定,这样做更好吗:

To declare an empty slice, with a non-fixed size, is it better to do:

mySlice1 := make([]int, 0)

或:

mySlice2 := []int{}

只是想知道哪个是正确的方法.

Just wondering which one is the correct way.

推荐答案

您给出的两个替代方案在语义上是相同的,但是使用 make([]int, 0) 将导致内部调用runtime.makeslice(Go 1.16).

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.16).

您还可以选择将其保留为 nil 值:

You also have the option to leave it with a nil value:

var myslice []int

Golang.org 博客中所述:

nil 切片在功能上等同于零长度切片,即使它不指向任何内容.它的长度为零,可以附加到分配中.

a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

nil 切片将 json.Marshal() 转换为 "null" 而空切片将编组为 "[]",正如@farwayer 指出的那样.

A nil slice will however json.Marshal() into "null" whereas an empty slice will marshal into "[]", as pointed out by @farwayer.

正如@ArmanOrdookhani 所指出的,上述选项都不会导致任何分配.

None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.

这篇关于初始化空切片的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆