Skip to content

Commit f7061db

Browse files
committed
Update mem::replace example to not be identical to mem::take
This also adds assertions that the operations work as expected.
1 parent 0af8e87 commit f7061db

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/libcore/mem/mod.rs

+20-8
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,12 @@ pub fn swap<T>(x: &mut T, y: &mut T) {
552552
/// mem::take(&mut self.buf)
553553
/// }
554554
/// }
555+
///
556+
/// let mut buffer = Buffer { buf: vec![0, 1] };
557+
/// assert_eq!(buffer.buf.len(), 2);
558+
///
559+
/// assert_eq!(buffer.get_and_reset(), vec![0, 1]);
560+
/// assert_eq!(buffer.buf.len(), 0);
555561
/// ```
556562
///
557563
/// [`Clone`]: ../../std/clone/trait.Clone.html
@@ -586,17 +592,17 @@ pub fn take<T: Default>(dest: &mut T) -> T {
586592
/// struct Buffer<T> { buf: Vec<T> }
587593
///
588594
/// impl<T> Buffer<T> {
589-
/// fn get_and_reset(&mut self) -> Vec<T> {
595+
/// fn replace_index(&mut self, i: usize, v: T) -> T {
590596
/// // error: cannot move out of dereference of `&mut`-pointer
591-
/// let buf = self.buf;
592-
/// self.buf = Vec::new();
593-
/// buf
597+
/// let t = self.buf[i];
598+
/// self.buf[i] = v;
599+
/// t
594600
/// }
595601
/// }
596602
/// ```
597603
///
598-
/// Note that `T` does not necessarily implement [`Clone`], so it can't even clone and reset
599-
/// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
604+
/// Note that `T` does not necessarily implement [`Clone`], so we can't even clone `self.buf[i]` to
605+
/// avoid the move. But `replace` can be used to disassociate the original value at that index from
600606
/// `self`, allowing it to be returned:
601607
///
602608
/// ```
@@ -605,10 +611,16 @@ pub fn take<T: Default>(dest: &mut T) -> T {
605611
///
606612
/// # struct Buffer<T> { buf: Vec<T> }
607613
/// impl<T> Buffer<T> {
608-
/// fn get_and_reset(&mut self) -> Vec<T> {
609-
/// mem::replace(&mut self.buf, Vec::new())
614+
/// fn replace_index(&mut self, i: usize, v: T) -> T {
615+
/// mem::replace(&mut self.buf[i], v)
610616
/// }
611617
/// }
618+
///
619+
/// let mut buffer = Buffer { buf: vec![0, 1] };
620+
/// assert_eq!(buffer.buf[0], 0);
621+
///
622+
/// assert_eq!(buffer.replace_index(0, 2), 0);
623+
/// assert_eq!(buffer.buf[0], 2);
612624
/// ```
613625
///
614626
/// [`Clone`]: ../../std/clone/trait.Clone.html

0 commit comments

Comments
 (0)