Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to add an append method to a slice

Tags:

arrays

go

I have something like the following type structure below:

type Set []*Element

func (set *Set) AppendElements(elements []*Elements) {
    // ?
}

Obviously simply appending elements to a slice is not very useful. However, the actual function takes some value, does some business logic, and then appends the elements. However, I am facing the difficulty that modifications to the slice inside of the method to not actually change the value of the slice to outside callers, because the append method allocates a new slice that is not seen by the callers.

Is there a way to append to the slice in a method or should the slice be wrapped in a struct or something else?

package main

import "fmt"

type Element int
type Set []*Element

func (ptr *Set) AppendElements(elements []*Element) {
    set := *ptr
    set = append(set, elements...)
}

func main() {
    i := Element(1)
    var set Set
    set.AppendElements([]*Element{&i})

    for _, el := range set {
        fmt.Println(el)
    }
}

More specifically, the above prints nothing.

like image 881
xaav Avatar asked Oct 20 '25 15:10

xaav


1 Answers

You're modifying the slice, but you never assign it back to the pointer.

func (ptr *Set) AppendElements(elements []*Element) {
    set := *ptr
    set = append(set, elements...)
    *ptr = set
}

Usually though, one would dereference the pointer directly in the append statement:

func (set *Set) AppendElements(elements []*Element) {
    *set = append(*set, elements...)
}
like image 171
JimB Avatar answered Oct 23 '25 05:10

JimB