Max
Max

Reputation: 29

Create method to a slice type

I am new to golang. I am trying to add a method to a slice. The method is just a wrapper of append, which does not work.

package main

import (
    "fmt"
)

type SliceStr []string

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

func main() {
    var s SliceStr

    s.Add("hello")
    fmt.Println(s)
}

prog.go:10:12: first argument to append must be slice; have *SliceStr

Upvotes: 0

Views: 476

Answers (1)

Leon
Leon

Reputation: 3036

You are getting a pointer to SliceStr (*SliceStr), not SliceStr and therefore not a slice-type. Just dereference the pointer

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

and it works just fine. *ss = ... sets the value ss is pointing to and the *ss in the call to append passes it the value ss is pointing to, instead of the pointer.

Upvotes: 4

Related Questions