Skip to content

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

@takanuva15

Description

@takanuva15

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions