@@ -141,6 +141,41 @@ impl<T> ToOwned for T
141
141
/// let mut input = Cow::from(vec![-1, 0, 1]);
142
142
/// abs_all(&mut input);
143
143
/// ```
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
+ /// ```
144
179
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
145
180
pub enum Cow < ' a , B : ?Sized + ' a >
146
181
where B : ToOwned
0 commit comments