Pass slice as function argument, and modify the original slice

If you want to pass a slice as a parameter to a function, and have that function modify the original slice, then you have to pass a pointer to the slice:

func myAppend(list *[]string, value string) {
    *list = append(*list, value)
}

I have no idea if the Go compiler is naive or smart about this; performance is left as an exercise for the comment section.

For junior coders out there, please note that this code is provided without error checking. For example, this code will panic if list is nil.

Leave a Comment