将()追加到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
    中取消对切片的引用

  • :

    go run plugin.go#命令行参数。/plugin.go:15:不能将append(*l,e)(type[]元素)用作赋值中的类型列表
    func (l *List) addElement(id string) {
        e := Element{
            Id: id,
        }
        *l = append(*l, e)
    }