Reputation: 3241
I want to append an element to a struct that only consists of a single annonymous slice:
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")
}
That does not work, since addElement does not know l as slice but as *List:
go run plugin.go
# command-line-arguments
./plugin.go:13: first argument to append must be slice; have *List
What most likely would work is to go like this:
type List struct {
elements []Element
}
and fix the addElement func accordingly. I there a nicer way than that, eg. one that let me keep the first definition of type List?
Many thanks, sontags
Upvotes: 4
Views: 7365