Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ForEachByRef to iterate over arrays by reference to elements #598

Open
takanuva15 opened this issue Feb 23, 2025 · 0 comments
Open

Add ForEachByRef to iterate over arrays by reference to elements #598

takanuva15 opened this issue Feb 23, 2025 · 0 comments

Comments

@takanuva15
Copy link

The existing lo.ForEach function makes a copy of every element as it iterates, which is problematic for arrays since that prevents them from being modified.

Example:

type Dummy struct {
	f1 string
}

a := []Dummy{{f1: "Hello"}}
fmt.Println(a)
lo.ForEach(a, func(d Dummy, _ int) {
	d.f1 += ", world!"
})
fmt.Println(a)

Output:

[{Hello}]
[{Hello}]

To resolve this, I would like to add a method ForEachByRef which would pass a ref to each array element in the function callback. With the new function, the above code would look like:

a := []Dummy{{f1: "Hello"}}
lo.ForEach(a, func(d *Dummy, _ int) {
	// etc...

If that sounds fine, can I raise a PR to add this function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant