pub enum Cow<'a, B>{ Borrowed(&'a B), Owned(<B asToOwned>::Owned),}Expand description
A clone-on-write smart pointer.
The typeCow is a smart pointer providing clone-on-write functionality: itcan enclose and provide immutable access to borrowed data, and clone thedata lazily when mutation or ownership is required. The type is designed towork with general borrowed data via theBorrow trait.
Cow implementsDeref, which means that you can callnon-mutating methods directly on the data it encloses. If mutationis desired,to_mut will obtain a mutable reference to an ownedvalue, cloning if necessary.
If you need reference-counting pointers, note thatRc::make_mut andArc::make_mut can provide clone-on-writefunctionality as well.
§Examples
usestd::borrow::Cow;fnabs_all(input:&mutCow<'_, [i32]>) {foriin0..input.len() {letv = input[i];ifv <0{// Clones into a vector if not already owned.input.to_mut()[i] = -v; } }}// No clone occurs because `input` doesn't need to be mutated.letslice = [0,1,2];letmutinput = Cow::from(&slice[..]);abs_all(&mutinput);// Clone occurs because `input` needs to be mutated.letslice = [-1,0,1];letmutinput = Cow::from(&slice[..]);abs_all(&mutinput);// No clone occurs because `input` is already owned.letmutinput = Cow::from(vec![-1,0,1]);abs_all(&mutinput);Another example showing how to keepCow in a struct:
usestd::borrow::Cow;structItems<'a, X>where[X]: ToOwned<Owned = Vec<X>> { values: Cow<'a, [X]>,}impl<'a, X: Clone +'a> Items<'a, X>where[X]: ToOwned<Owned = Vec<X>> {fnnew(v: Cow<'a, [X]>) ->Self{ Items { values: v } }}// Creates a container from borrowed values of a sliceletreadonly = [1,2];letborrowed = Items::new((&readonly[..]).into());matchborrowed { Items { values: Cow::Borrowed(b) } =>println!("borrowed {b:?}"),_=>panic!("expect borrowed value"),}letmutclone_on_write = borrowed;// Mutates the data from slice into owned vec and pushes a new value on topclone_on_write.values.to_mut().push(3);println!("clone_on_write = {:?}", clone_on_write.values);// The data was mutated. Let's check it out.matchclone_on_write { Items { values: Cow::Owned(_) } =>println!("clone_on_write contains owned data"),_=>panic!("expect owned data"),}Variants§
Implementations§
Source§impl<B>Cow<'_, B>
impl<B>Cow<'_, B>
Sourcepub const fnis_borrowed(c: &Cow<'_, B>) ->bool
🔬This is a nightly-only experimental API. (cow_is_borrowed #65143)
pub const fnis_borrowed(c: &Cow<'_, B>) ->bool
cow_is_borrowed #65143)Returns true if the data is borrowed, i.e. ifto_mut would require additional work.
Note: this is an associated function, which means that you have to callit asCow::is_borrowed(&c) instead ofc.is_borrowed(). This is sothat there is no conflict with a method on the inner type.
§Examples
Sourcepub const fnis_owned(c: &Cow<'_, B>) ->bool
🔬This is a nightly-only experimental API. (cow_is_borrowed #65143)
pub const fnis_owned(c: &Cow<'_, B>) ->bool
cow_is_borrowed #65143)Returns true if the data is owned, i.e. ifto_mut would be a no-op.
Note: this is an associated function, which means that you have to callit asCow::is_owned(&c) instead ofc.is_owned(). This is so thatthere is no conflict with a method on the inner type.
§Examples
1.0.0 ·Sourcepub fnto_mut(&mut self) -> &mut <B asToOwned>::Owned
pub fnto_mut(&mut self) -> &mut <B asToOwned>::Owned
Acquires a mutable reference to the owned form of the data.
Clones the data if it is not already owned.
§Examples
1.0.0 ·Sourcepub fninto_owned(self) -> <B asToOwned>::Owned
pub fninto_owned(self) -> <B asToOwned>::Owned
Extracts the owned data.
Clones the data if it is not already owned.
§Examples
Callinginto_owned on aCow::Borrowed returns a clone of the borrowed data:
usestd::borrow::Cow;lets ="Hello world!";letcow = Cow::Borrowed(s);assert_eq!( cow.into_owned(), String::from(s));Callinginto_owned on aCow::Owned returns the owned data. The data is moved out of theCow without being cloned.
Trait Implementations§
1.14.0 ·Source§impl<'a>AddAssign<&'astr> forCow<'a,str>
impl<'a>AddAssign<&'astr> forCow<'a,str>
Source§fnadd_assign(&mut self, rhs: &'astr)
fnadd_assign(&mut self, rhs: &'astr)
+= operation.Read more1.52.0 ·Source§impl<'a>Extend<Cow<'a,OsStr>> forOsString
impl<'a>Extend<Cow<'a,OsStr>> forOsString
1.19.0 ·Source§impl<'a>Extend<Cow<'a,str>> forString
impl<'a>Extend<Cow<'a,str>> forString
1.45.0 ·Source§implFrom<Cow<'_,str>> forBox<str>
implFrom<Cow<'_,str>> forBox<str>
Source§fnfrom(cow:Cow<'_,str>) ->Box<str>
fnfrom(cow:Cow<'_,str>) ->Box<str>
Converts aCow<'_, str> into aBox<str>
Whencow is theCow::Borrowed variant, thisconversion allocates on the heap and copies theunderlyingstr. Otherwise, it will try to reuse the ownedString’s allocation.