Skip to content

Commit cbbfcc5

Browse files
authored
Rollup merge of rust-lang#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.
2 parents 5b74d67 + 5bfb785 commit cbbfcc5

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/liballoc/borrow.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,41 @@ impl<T> ToOwned for T
141141
/// let mut input = Cow::from(vec![-1, 0, 1]);
142142
/// abs_all(&mut input);
143143
/// ```
144+
///
145+
/// Another example showing how to keep `Cow` in a struct:
146+
///
147+
/// ```
148+
/// use std::borrow::{Cow, ToOwned};
149+
///
150+
/// struct Items<'a, X: 'a> where [X]: ToOwned<Owned=Vec<X>> {
151+
/// values: Cow<'a, [X]>,
152+
/// }
153+
///
154+
/// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned=Vec<X>> {
155+
/// fn new(v: Cow<'a, [X]>) -> Self {
156+
/// Items { values: v }
157+
/// }
158+
/// }
159+
///
160+
/// // Creates a container from borrowed values of a slice
161+
/// let readonly = [1, 2];
162+
/// let borrowed = Items::new((&readonly[..]).into());
163+
/// match borrowed {
164+
/// Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
165+
/// _ => panic!("expect borrowed value"),
166+
/// }
167+
///
168+
/// let mut clone_on_write = borrowed;
169+
/// // Mutates the data from slice into owned vec and pushes a new value on top
170+
/// clone_on_write.values.to_mut().push(3);
171+
/// println!("clone_on_write = {:?}", clone_on_write.values);
172+
///
173+
/// // The data was mutated. Let check it out.
174+
/// match clone_on_write {
175+
/// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
176+
/// _ => panic!("expect owned data"),
177+
/// }
178+
/// ```
144179
#[stable(feature = "rust1", since = "1.0.0")]
145180
pub enum Cow<'a, B: ?Sized + 'a>
146181
where B: ToOwned

0 commit comments

Comments
 (0)