diff options
| author | bors <bors@rust-lang.org> | 2020-11-21 08:15:16 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2020-11-21 08:15:16 +0000 |
| commit | 29a74e62857bc8c51723402dee5873ef0fe2cd83 (patch) | |
| tree | 58867f7cbb95a94e036cd862c946a77b2a981022 | |
| parent | 502c477b3417f18e4e45b4e6e37da9965a033051 (diff) | |
| parent | a64d0d4774db30bd37ec2ede87e966dcdd33dfc2 (diff) | |
| download | rust-29a74e62857bc8c51723402dee5873ef0fe2cd83.tar.gz rust-29a74e62857bc8c51723402dee5873ef0fe2cd83.zip | |
Auto merge of #79222 - yoshuawuyts:slice-fill-with, r=m-ou-se
Add `core::slice::fill_with` Tracking issue https://github.com/rust-lang/rust/issues/79221. As suggested by `@m-ou-se` in https://github.com/rust-lang/rust/issues/70758#issuecomment-726838099 this implements `slice::fill_with` as a counterpart to `slice::fill`. This mirrors `Vec::resize` and `Vec::resize_with`. Thanks! r? `@m-ou-se`
| -rw-r--r-- | library/core/src/slice/mod.rs | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index c50aa18caf6..83f22895237 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -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`. |
