From bcc901260ce5b2b0a832ca68464f069b6d56a63c Mon Sep 17 00:00:00 2001 From: Chloe Ross Date: Fri, 18 Sep 2020 21:05:24 -0700 Subject: [PATCH] add `slice::replace` --- library/core/src/slice/mod.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index fd98f60c3ddc6..362c2e2cf378d 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -3059,6 +3059,30 @@ impl [T] { left } + + /// Moves `value` into `self[index]`, returning the old value. + /// + /// Neither value is dropped. + /// + /// # Panics + /// + /// Panics if `index` is out of bounds. + /// + /// # Examples + /// + /// ``` + /// #![feature(slice_replace)] + /// + /// let mut v = [1, 2, 3]; + /// let r = v.replace(1, 20); + /// + /// assert_eq!(v, [1, 20, 3]); + /// assert_eq!(r, 2); + /// ``` + #[unstable(feature = "slice_replace", reason = "new API", issue = "none")] + pub fn replace(&mut self, index: usize, value: T) -> T { + mem::replace(&mut self[index], value) + } } #[stable(feature = "rust1", since = "1.0.0")]