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

improve array_from_fn documenation #104839

Merged
merged 2 commits into from
Nov 26, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions library/core/src/array/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ mod iter;
#[stable(feature = "array_value_iter", since = "1.51.0")]
pub use iter::IntoIter;

/// Creates an array `[T; N]` where each array element `T` is returned by the `cb` call.
/// Creates an array of type [T; N], where each element `T` is the returned value from `cb`
/// using that element's index.
///
/// # Arguments
///
Expand All @@ -36,8 +37,18 @@ pub use iter::IntoIter;
/// // elements to produce is the length of array down there: only arrays of
/// // equal lengths can be compared, so the const generic parameter `N` is
/// // inferred to be 5, thus creating array of 5 elements.
/// let array = core::array::from_fn(|i| i);
///
/// let array: [_; 5] = core::array::from_fn(|i| i);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given the big comment about type inference above this one, I think this example should stay of inferred width

Suggested change
/// let array: [_; 5] = core::array::from_fn(|i| i);
/// let array = core::array::from_fn(|i| i);

/// // indexes are: 0 1 2 3 4
/// assert_eq!(array, [0, 1, 2, 3, 4]);
///
/// let array2: [_; 8] = core::array::from_fn(|i| i * 2);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then it would be good to mention the type annotation on this on to contrast with the first one.

/// // indexes are: 0 1 2 3 4 5 6 7
/// assert_eq!(array2, [0, 2, 4, 6, 8, 10, 12, 14]);
///
/// let bool_arr: [bool; 5] = core::array::from_fn(|i| i % 2 == 0);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And for completeness, maybe show turbofishing for this one?

Suggested change
/// let bool_arr: [bool; 5] = core::array::from_fn(|i| i % 2 == 0);
/// let bool_arr = core::array::from_fn::<_, 5, _>(|i| i % 2 == 0);

/// // indexes are: 0 1 2 3 4
/// assert_eq!(bool_arr, [true, false, true, false, true]);
/// ```
#[inline]
#[stable(feature = "array_from_fn", since = "1.63.0")]
Expand Down