-
Notifications
You must be signed in to change notification settings - Fork 17.7k
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
proposal: slices: add ForEach function to iterate #70177
Comments
I believe in the general case this is Map, which would be part of iterators not slices, see #61898 |
No, in the iterator age, the code should be like package main
import "fmt"
func ForEach[T any](s []T, f func(T)) func(func() bool) {
return func(yield func() bool) {
for _, v := range s {
f(v)
if !yield() {
return
}
}
}
}
type BankAccount struct {
Balance int
}
func printBalance(account *BankAccount) {
fmt.Println(account.Balance)
}
func main() {
accounts := []*BankAccount{{100}, {200}, {300}}
for range ForEach(accounts, printBalance) {}
} :) |
Or even more graceful: package main
import (
"fmt"
"slices"
)
func ForEach[E any](it func(func(V E) bool), f func(V E)) func(func() bool) {
return func(yield func() bool) {
for v := range it {
f(v)
if !yield() {
return
}
}
}
}
type BankAccount struct {
Balance int
}
func printBalance(account *BankAccount) {
fmt.Println(account.Balance)
}
func main() {
accounts := []*BankAccount{{100}, {200}, {300}}
for range ForEach(slices.Values(accounts), printBalance) {}
} |
It's not |
Thank you for your feedback.
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Proposal Details
Abstract
This proposal suggests adding a
ForEach
function to Go slices, inspired by thestd::for_each
function in C++. This function would simplify the iteration process over slices, providing a clear and concise way to apply a function to each element of a slice, enhancing readability and code organization.Proposal
Add a function
ForEach
with a possible implementation like:This function will allow users to apply a specified function to each element in a slice without the need for a for loop, improving a lot readability in situations like this example:
A ForEach function lets us directly express the intent of the looping which in my opinion improves a lot readability and comprehension of a code, while being as concise as possible.
If community aggrees with the proposal, I would be happy to provide a PR with implementation.
Thank you
The text was updated successfully, but these errors were encountered: