Skip to content

Commit

Permalink
Rollup merge of rust-lang#79222 - yoshuawuyts:slice-fill-with, r=m-ou-se
Browse files Browse the repository at this point in the history
Add `core::slice::fill_with`

Tracking issue rust-lang#79221.

As suggested by `@m-ou-se` in rust-lang#70758 (comment) this implements `slice::fill_with` as a counterpart to `slice::fill`. This mirrors `Vec::resize` and `Vec::resize_with`. Thanks!

r? `@m-ou-se`
  • Loading branch information
Dylan-DPC committed Nov 21, 2020
2 parents 642de64 + a64d0d4 commit 7af4939
Showing 1 changed file with 28 additions and 0 deletions.
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`]
/// 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);
/// 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

0 comments on commit 7af4939

Please sign in to comment.