Enum collections::borrow::Cow
[−]
[src]
pub enum Cow<'a, B: ?Sized + 'a> where B: ToOwned {
Borrowed(&'a B),
Owned(B::Owned),
}
1.0.0A clone-on-write smart pointer.
The type Cow
is a smart pointer providing clone-on-write functionality: it
can enclose and provide immutable access to borrowed data, and clone the
data lazily when mutation or ownership is required. The type is designed to
work with general borrowed data via the Borrow
trait.
Cow
implements Deref
, which means that you can call
non-mutating methods directly on the data it encloses. If mutation
is desired, to_mut
will obtain a mutable reference to an owned
value, cloning if necessary.
Examples
fn main() { use std::borrow::Cow; #[allow(dead_code)] fn abs_all(input: &mut Cow<[i32]>) { for i in 0..input.len() { let v = input[i]; if v < 0 { // clones into a vector the first time (if not already owned) input.to_mut()[i] = -v; } } } }use std::borrow::Cow; fn abs_all(input: &mut Cow<[i32]>) { for i in 0..input.len() { let v = input[i]; if v < 0 { // clones into a vector the first time (if not already owned) input.to_mut()[i] = -v; } } }
Variants
Borrowed | Borrowed data. | |
Owned | Owned data. |
Methods
impl<'a, B: ?Sized> Cow<'a, B> where B: ToOwned
fn to_mut(&mut self) -> &mut B::Owned
Acquires a mutable reference to the owned form of the data.
Clones the data if it is not already owned.
Examples
fn main() { use std::borrow::Cow; let mut cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]); let hello = cow.to_mut(); assert_eq!(hello, &[1, 2, 3]); }use std::borrow::Cow; let mut cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]); let hello = cow.to_mut(); assert_eq!(hello, &[1, 2, 3]);
fn into_owned(self) -> B::Owned
Extracts the owned data.
Clones the data if it is not already owned.
Examples
fn main() { use std::borrow::Cow; let cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]); let hello = cow.into_owned(); assert_eq!(vec![1, 2, 3], hello); }use std::borrow::Cow; let cow: Cow<[_]> = Cow::Owned(vec![1, 2, 3]); let hello = cow.into_owned(); assert_eq!(vec![1, 2, 3], hello);