Go – 初始化一个空切片

huangapple go评论68阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2016年9月15日 00:54:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/39495877.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定