diff options
| author | Pietro Albini <pietro@pietroalbini.org> | 2018-08-30 20:15:25 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2018-08-30 20:15:25 +0200 |
| commit | 2531d43f19753366c551b3fe5a34658cf34f5f06 (patch) | |
| tree | 14020a4225500577634fc1545326ed09738bc03e /src/liballoc | |
| parent | b7e74a56140d4a89d0cf917788f16d8134d79eb4 (diff) | |
| parent | 5bfb7850782c440f27e0a5b64157aed9e04c5cc6 (diff) | |
| download | rust-2531d43f19753366c551b3fe5a34658cf34f5f06.tar.gz rust-2531d43f19753366c551b3fe5a34658cf34f5f06.zip | |
Rollup merge of #53113 - kpp:more_docs_for_cow, r=GuillaumeGomez
Add example for Cow Add one more example that shows how to keep `Cow` in a struct. Link to playground: https://play.rust-lang.org/?gist=a9256bdd034b44bc3cdd0044bbcdbb7c&version=stable&mode=debug&edition=2015 Users ask this question in [ruRust](https://gitter.im/ruRust/general) chat time to time and it is not obvious to add `ToOwned<Owned=Target>` to requirements of generic params.
Diffstat (limited to 'src/liballoc')
| -rw-r--r-- | src/liballoc/borrow.rs | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/src/liballoc/borrow.rs b/src/liballoc/borrow.rs index c6741ddb822..5ae5339138f 100644 --- a/src/liballoc/borrow.rs +++ b/src/liballoc/borrow.rs @@ -141,6 +141,41 @@ impl<T> ToOwned for T /// let mut input = Cow::from(vec![-1, 0, 1]); /// abs_all(&mut input); /// ``` +/// +/// Another example showing how to keep `Cow` in a struct: +/// +/// ``` +/// 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 |
