英文:
Go - initialize an empty slice
问题
声明一个空切片时,我知道你应该优先选择:
var t []string
而不是
t := []string{}
因为它不会分配不必要的内存(https://github.com/golang/go/wiki/CodeReviewComments#declaring-empty-slices)。如果我有以下代码,这个规则是否仍然适用:
type example struct {
s []string
}
e := &example{}
也就是说,是使用
e.s = []string{}
还是
var s []string
e.s = s
英文:
To declare an empty slice, I know that you should prefer
var t []string
over
t := []string{}
as it doesn't allocate unecessary memory (https://github.com/golang/go/wiki/CodeReviewComments#declaring-empty-slices). Does this still apply if I have
type example struct {
s []string
}
e := &example{}
i.e. would it be better to use
e.s = []string{}
or
var s []string
e.s = s
答案1
得分: 2
example.s
已经声明,所以你不需要做任何事情。
e := &example{}
e.s = append(e.s, "val")
fmt.Println(e.s)
英文:
example.s
is already declared, so there's nothing you need to do.
e := &example{}
e.s = append(e.s, "val")
fmt.Println(e.s)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论