Skip to content

Commit 931eb4c

Browse files
committed
Add one more example for Cow that shows how to keep Cow in a struct
1 parent 78ec12d commit 931eb4c

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/liballoc/borrow.rs

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

0 commit comments

Comments
 (0)