diff options
| author | Roman Proskuryakov <humbug@deeptown.org> | 2018-08-06 17:33:32 +0300 |
|---|---|---|
| committer | Roman Proskuryakov <humbug@deeptown.org> | 2018-08-06 17:33:32 +0300 |
| commit | 931eb4c4d5169ebff249387f2049295eb7925c79 (patch) | |
| tree | 65cd6c8c9e24ff59822ec1fe40c9e18b26527a6f /src/liballoc | |
| parent | 78ec12df020453836c3b8990c0a8dd859b774e84 (diff) | |
| download | rust-931eb4c4d5169ebff249387f2049295eb7925c79.tar.gz rust-931eb4c4d5169ebff249387f2049295eb7925c79.zip | |
Add one more example for Cow that shows how to keep Cow in a struct
Diffstat (limited to 'src/liballoc')
| -rw-r--r-- | src/liballoc/borrow.rs | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/src/liballoc/borrow.rs b/src/liballoc/borrow.rs index c6741ddb822..dd4f958804d 100644 --- a/src/liballoc/borrow.rs +++ b/src/liballoc/borrow.rs @@ -141,6 +141,40 @@ impl<T> ToOwned for 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 |
