php editor Apple will introduce how to expose slice members with immutability. In programming, slicing refers to the operation of intercepting a part of elements or characters from an array or string. Normally, a slicing operation returns a new array or string, but sometimes we want to keep the original array or string unchanged and expose only some members of the slice. Doing so can improve your program's performance and memory utilization. Next, we'll detail how to accomplish this.
I have a struct with a slice member, and a method that exposes the slice. But I don't want the caller to be able to change the contents of the slice. If I do:
type a struct { slice []int } func (a *a) list() []int { return a.slice }
It is not safe because 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 avoid this by having list()
return a copy of the slice:
func (a *A) list() []int { return append([]int{}, a.slice...) }
Once you provide the slice to an external caller by returning it, it can be modified. If copying is not acceptable for performance reasons, you can implement visitors:
func (a *a) visit(f func(int)) { for _, v := range a.slice { f(v) } }
This does not expose the slice at all, and allows client code to view all items in the slice at once. If the items are not pointers or other mutable types, this is effectively read-only because the visitor callback will receive a copy of the value.
If you want to stop iteration early, the visitor can return a boolean value (optional).
func (a *A) Visit(f func(int) bool) { for _, v := range a.slice { if !f(v) { return } } }
The above is the detailed content of How to expose slice members with immutability?. For more information, please follow other related articles on the PHP Chinese website!