Skip to content

Commit

Permalink
Rollup merge of rust-lang#53113 - kpp:more_docs_for_cow, r=GuillaumeG…
Browse files Browse the repository at this point in the history
…omez

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.
  • Loading branch information
kennytm committed Aug 28, 2018
2 parents 5b74d67 + 5bfb785 commit cbbfcc5
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/liballoc/borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit cbbfcc5

Please sign in to comment.