monkey
monkey

Reputation: 1279

How to modify type slice inside method?

How to modify type slice inside method? I tried http://play.golang.org/p/ul2n8mk6ye

type Test []string

func (test Test) Add(str string) {
    test = append(test, str)
}

func main() {
    test := Test{}
    test.Add("value")
    fmt.Println(len(test))//0
}

And http://play.golang.org/p/nV9IO7E5sp

type Test []string

func (test *Test) Add(str string) {
    v := append(*test, str)
    test = &v
}

func main() {
        test := Test{}
    test.Add("value")
    fmt.Println(len(test))//0
}

But it does not work.

Upvotes: 0

Views: 161

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109377

You need to use a pointer receiver, which you've tried in your second example, but you then overwrite the pointer value which defeats the purpose.

You could use

func (test *Test) Add(str string) {
    v := append(*test, str)
    *test = v
}

Or more clearly:

func (test *Test) Add(str string) {
    *test = append(*test, str)
}

Upvotes: 2

Related Questions