Slice pass as value or pointer?

Indeed. So to answer the question in the topic title, it’s idiomatic to have functions like slice = doSomethingWithSlice(slice) and less so to see doSomethingWithSlice(&slice). An exception is when you declare methods on a slice type (1) as those will by necessity have pointer-to-slice receivers if they intend to modify the slice;

type fibSlice []int

func (sp *fibSlice) append() {
	s := *sp
	l := len(s)

	switch l {
	case 0:
		*sp = append(s, 0)
	case 1:
		*sp = append(s, 1)
	default:
		*sp = append(s, s[l-1]+s[l-2])
	}
}

I avoided some of the incessant “starring” by the s := *sp but it still gets annoying rather quickly. It’s usually neater to just declare a struct type containing the slice if I’m going to do to much of this.

1 Like