Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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

like image 704
sontags Avatar asked Oct 21 '25 04:10

sontags


1 Answers

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)
}
like image 119
OneOfOne Avatar answered Oct 22 '25 17:10

OneOfOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!