Skip to content

Commit 29a74e6

Browse files
committed
Auto merge of #79222 - yoshuawuyts:slice-fill-with, r=m-ou-se
Add `core::slice::fill_with` Tracking issue #79221. As suggested by `@m-ou-se` in #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`
2 parents 502c477 + a64d0d4 commit 29a74e6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

library/core/src/slice/mod.rs

+28
Original file line numberDiff line numberDiff line change
@@ -2599,6 +2599,34 @@ impl<T> [T] {
25992599
}
26002600
}
26012601

2602+
/// Fills `self` with elements returned by calling a closure repeatedly.
2603+
///
2604+
/// This method uses a closure to create new values. If you'd rather
2605+
/// [`Clone`] a given value, use [`fill`]. If you want to use the [`Default`]
2606+
/// trait to generate values, you can pass [`Default::default`] as the
2607+
/// argument.
2608+
///
2609+
/// [`fill`]: #method.fill
2610+
///
2611+
/// # Examples
2612+
///
2613+
/// ```
2614+
/// #![feature(slice_fill_with)]
2615+
///
2616+
/// let mut buf = vec![1; 10];
2617+
/// buf.fill_with(Default::default);
2618+
/// assert_eq!(buf, vec![0; 10]);
2619+
/// ```
2620+
#[unstable(feature = "slice_fill_with", issue = "79221")]
2621+
pub fn fill_with<F>(&mut self, mut f: F)
2622+
where
2623+
F: FnMut() -> T,
2624+
{
2625+
for el in self {
2626+
*el = f();
2627+
}
2628+
}
2629+
26022630
/// Copies the elements from `src` into `self`.
26032631
///
26042632
/// The length of `src` must be the same as `self`.

0 commit comments

Comments
 (0)