-
Notifications
You must be signed in to change notification settings - Fork 12.8k
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 core::array::from_fn
#83576
Add core::array::from_fn
#83576
Conversation
(rust-highfive has picked a reviewer for you, use r? to override) |
Would it make sense to pass the index? Iterators can be infinite so it doesn't make sense there, but that doesn't apply to arrays. |
This comment has been minimized.
This comment has been minimized.
This adds `core::array::from_fn` for initializing an array from a closure. The API is meant to closely resemble `core::iter::from_fn` with the difference that the array dictates the amount of elements produced as opposed to the function. This should also cover a lot of cases where one might want to reach for collecting into an array, but without all the associated problems that this would have, such as providing too few or too many elements. ```rust let array = std::array::from_fn(|index| 2 * index); assert_eq!(array, [0, 2, 4, 6]); ```
I think this is very similar to #75644. |
r? @joshtriplett but I imagine we may want to (temporarily at least) close in favor of #75644 as noted by @voidc |
I'd suggest that we discuss on #75644 which PR should get merged. I do favor the naming from this PR, but I don't have an opinion on which PR should be merged other than naming. |
☔ The latest upstream changes (presumably #84525) made this pull request unmergeable. Please resolve the merge conflicts. |
I'll close this in favor of #75644 which also implements the |
This adds
core::array::from_fn
for initializing an array from a closure. The API is meant to closely resemblecore::iter::from_fn
with the difference that the array dictates the amount of elements produced as opposed to the function.This should also cover a lot of cases where one might want to reach for collecting into an array, but without all the associated problems that this would have, such as providing too few or too many elements.
Example Usage