append()表示在golang中只有一个切片字段

son*_*ags 3 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.addElement("test")
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为addElement不知道l作为切片而是作为*List:

go run plugin.go
# command-line-arguments
./plugin.go:13: first argument to append must be slice; have *List
Run Code Online (Sandbox Code Playgroud)

最有可能的是这样:

type List struct {
    elements []Element
}
Run Code Online (Sandbox Code Playgroud)

并相应地修复addElement func.我有一个比这更好的方法,例如.让我保留List类型的第一个定义的一个?

非常感谢,sontags

One*_*One 7

两个问题,

  1. 要追加*Element[]Element,无论是使用Element{}或更改列表[]*Element.

  2. 您需要取消引用切片addElement.

示例:

func (l *List) addElement(id string) {
    e := Element{
        Id: id,
    }
    *l = append(*l, e)
}
Run Code Online (Sandbox Code Playgroud)