I have a struct with a slice member, and a method to expose this slice. But I don't want the caller being able to change the content of the slice. If I do this:
type A struct {
slice []int
}
func (a *A) list() []int {
return a.slice
}
it is not safe, as the content can be easily modified:
a := A{[]int{1, 2, 3}}
_ = append(a.list()[:2], 4)
fmt.Println(a.list()) // [1 2 4]
Obviously I can let list()
return a copy of the slice to avoid this:
func (a *A) list() []int {
return append([]int{}, a.slice...)
}
but that means every time when I just want to iterate through the slice I created a copy, which seems wasteful. Is there a way to do this without unnecessary copying?