将()追加到golang中只有一个切片字段的stuct
我想将一个元素附加到只包含单个注释性切片的结构中:将()追加到golang中只有一个切片字段的stuct,go,Go,我想将一个元素附加到只包含单个注释性切片的结构中: package main type List []Element type Element struct { Id string } func (l *List) addElement(id string) { e := &Element{ Id: id, } l = append(l, e) } func main() { list := List{} list.
package main
type List []Element
type Element struct {
Id string
}
func (l *List) addElement(id string) {
e := &Element{
Id: id,
}
l = append(l, e)
}
func main() {
list := List{}
list.addElement("test")
}
这不起作用,因为addElement不知道l是slice,而是*List:
go run plugin.go
# command-line-arguments
./plugin.go:13: first argument to append must be slice; have *List
最有可能起作用的是这样:
type List struct {
elements []Element
}
并相应地修改addElement func。我知道还有比这更好的方法吗,例如,让我保留类型列表的第一个定义
非常感谢,sontags两个问题
*元素
附加到[]元素
,请使用元素{}
或将列表更改为[]*元素
addElement
中取消对切片的引用func (l *List) addElement(id string) {
e := Element{
Id: id,
}
*l = append(*l, e)
}