]> git.lizzy.rs Git - rust.git/commitdiff
Add one more example for Cow that shows how to keep Cow in a struct
authorRoman Proskuryakov <humbug@deeptown.org>
Mon, 6 Aug 2018 14:33:32 +0000 (17:33 +0300)
committerRoman Proskuryakov <humbug@deeptown.org>
Mon, 6 Aug 2018 14:33:32 +0000 (17:33 +0300)
src/liballoc/borrow.rs

index c6741ddb822d5bb9114889bc71fdd2203f72e559..dd4f958804dee0db8e0bee597c0144e2b88d1f07 100644 (file)
@@ -141,6 +141,40 @@ fn clone_into(&self, target: &mut T) {
 /// let mut input = Cow::from(vec![-1, 0, 1]);
 /// abs_all(&mut input);
 /// ```
+///
+/// ```
+/// use std::borrow::{Cow, ToOwned};
+///
+/// struct Items<'a, X: 'a> where [X]: ToOwned<Owned=Vec<X>> {
+///     values: Cow<'a, [X]>,
+/// }
+///
+/// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned=Vec<X>> {
+///     fn new(v: Cow<'a, [X]>) -> Self {
+///         Items { values: v }
+///     }
+/// }
+///
+/// // Creates a container from borrowed values of a slice
+/// let readonly = [1, 2];
+/// let borrowed = Items::new((&readonly[..]).into());
+/// match borrowed {
+///     Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
+///     _ => panic!("expect borrowed value"),
+/// }
+///
+/// let mut clone_on_write = borrowed;
+/// // Mutates the data from slice into owned vec and pushes a new value on top
+/// clone_on_write.values.to_mut().push(3);
+/// println!("clone_on_write = {:?}", clone_on_write.values);
+///
+/// // The data was mutated. Let check it out.
+/// match clone_on_write {
+///     Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
+///     _ => panic!("expect owned data"),
+/// }
+/// ```
+
 #[stable(feature = "rust1", since = "1.0.0")]
 pub enum Cow<'a, B: ?Sized + 'a>
     where B: ToOwned