0

When I tried to add a new method to an aliased type, append method not works.

package main

import (
  "fmt"
)
    type Strings []string

func (ss Strings) Add(s string) {
    ss = append(ss, s)
}

func main() {
    ss := make(Strings, 0)

    ss = append(ss, "haha", "h3h3")
    fmt.Println(ss) // got [haha h3h3]


    ss.Add("lala")
    fmt.Println(ss) // also got [haha h3h3], and why ?
}

Why doesn't "lala" get appended to ss?

Leo Correa
  • 19,131
  • 2
  • 53
  • 71
Bill Xiong
  • 91
  • 1
  • 3
  • 1
    In short, if `Add()` may modify the receiver, the receiver must be a pointer: `func (ss *Strings) Add(s string) { *ss = append(*ss, s) }`. Try it on the [Go Playground](https://play.golang.org/p/JZSewRx9al). – icza Oct 10 '17 at 12:17
  • Thanks @icza , it works now. – Bill Xiong Oct 10 '17 at 12:20

0 Answers0