How to expose slice members with immutability?

PHPz
Release: 2024-02-09 09:20:11
forward
635 people have browsed it

How to expose slice members with immutability?

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.

Question content

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
}
Copy after login

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]
Copy after login

Obviously I can avoid this by having list() return a copy of the slice:

func (a *A) list() []int {
    return append([]int{}, a.slice...)
}
Copy after login
But this means I'm creating a copy every time I just want to iterate over the slice, which seems wasteful. Is there a way to do this without unnecessary copying?

Workaround

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)
    }
}
Copy after login

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
        }
    }
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!