sontags
sontags

Reputation: 3241

append() to stuct that only has one slice field in golang

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

Answers (1)

OneOfOne
OneOfOne

Reputation: 99274

Two problems,

  1. You're appending *Element to []Element, either use Element{} or change the list to []*Element.

  2. You need to dereference the slice in addElement.

Example:

func (l *List) addElement(id string) {
    e := Element{
        Id: id,
    }
    *l = append(*l, e)
}

Upvotes: 9

Related Questions