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 core::slice::fill_with #79222

Merged
merged 1 commit into from
Nov 21, 2020
Merged
Changes from all commits
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
28 changes: 28 additions & 0 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2599,6 +2599,34 @@ impl<T> [T] {
}
}

/// Fills `self` with elements returned by calling a closure repeatedly.
///
/// This method uses a closure to create new values. If you'd rather
/// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
yoshuawuyts marked this conversation as resolved.
Show resolved Hide resolved
/// trait to generate values, you can pass [`Default::default`] as the
/// argument.
///
/// [`fill`]: #method.fill
///
/// # Examples
///
/// ```
/// #![feature(slice_fill_with)]
///
/// let mut buf = vec![1; 10];
/// buf.fill_with(Default::default);
yoshuawuyts marked this conversation as resolved.
Show resolved Hide resolved
/// assert_eq!(buf, vec![0; 10]);
/// ```
#[unstable(feature = "slice_fill_with", issue = "79221")]
pub fn fill_with<F>(&mut self, mut f: F)
where
F: FnMut() -> T,
{
for el in self {
*el = f();
}
}

/// Copies the elements from `src` into `self`.
///
/// The length of `src` must be the same as `self`.
Expand Down