Slice Methods

In Go, slices can have methods too (indirectly). There can be so many use cases when slices can have methods. Have you ever come across a situation where you had a struct satisfying an interface but you had a slice of the same struct and hence you had to iterate over the slice and pass a single item eachtime to some function that accepted this interface? and imagine doing that multiple times in your code. Well, you don’t have to do that, there is a way for slices to have their own methods.

It can be achieved in the following way -


type Todo struct {
    ID      int
    Content string
}

type TodoSlice []Todo

func (ts TodoSlice) String() (s string) {
    t := []Todo(ts)
    s = fmt.Sprintln("No of Todos:", len(t), "\n")
    for i, todo := range t {
        s += fmt.Sprintln(i, " -")
        s += fmt.Sprintln(" ID: ", todo.ID)
        s += fmt.Sprintln(" Content: ", todo.Content)
        s += fmt.Sprintln("\n")
    }
    return
}
func main() {
    t1 := Todo{2, `Go Rocks !!`}
    t2 := Todo{5, `Methods on slices are cool!!`}
    todos := []Todo{t1, t2}
    fmt.Println(TodoSlice(todos))
}

You can run this code here.

In the above example, I created a type TodoSlice which is of type slice of type Todo. This new type has a method String() string, this method can be called on the slice of struct Todo by casting it to type TodoSlice. What we now indirectly have is a method on slice of type Todo, since it has a method, it can also satisfy an interface.

comments powered by Disqus
comments powered by Disqus