Skip to main content

Cow

Enum Cow 

1.36.0 ยท Source
pub enum Cow<'a, B>
where B: ToOwned + ?Sized + 'a,
{ Borrowed(&'a B), Owned(<B as ToOwned>::Owned), }
Expand description

A 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.

If you need reference-counting pointers, note that Rc::make_mut and Arc::make_mut can provide clone-on-write functionality as well.

ยงExamples

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 if not already owned.
            input.to_mut()[i] = -v;
        }
    }
}

// No clone occurs because `input` doesn't need to be mutated.
let slice = [0, 1, 2];
let mut input = Cow::from(&slice[..]);
abs_all(&mut input);

// Clone occurs because `input` needs to be mutated.
let slice = [-1, 0, 1];
let mut input = Cow::from(&slice[..]);
abs_all(&mut input);

// No clone occurs because `input` is already owned.
let mut input = Cow::from(vec![-1, 0, 1]);
abs_all(&mut input);

Another example showing how to keep Cow in a struct:

use std::borrow::Cow;

struct Items<'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>> {
    fn new(v: Cow<'a, [X]>) -> Self {
        Items { values: v }
    }
}

// Creates a container from borrowed values of a slice
let readonly = [1, 2];
let borrowed = Items::new((&readonly[..]).into());
match borrowed {
    Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
    _ => panic!("expect borrowed value"),
}

let mut clone_on_write = borrowed;
// Mutates the data from slice into owned vec and pushes a new value on top
clone_on_write.values.to_mut().push(3);
println!("clone_on_write = {:?}", clone_on_write.values);

// The data was mutated. Let's check it out.
match clone_on_write {
    Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
    _ => panic!("expect owned data"),
}

Variantsยง

ยง1.36.0

Borrowed(&'a B)

Borrowed data.

ยง1.36.0

Owned(<B as ToOwned>::Owned)

Owned data.

Implementationsยง

Sourceยง

impl<B: ?Sized + ToOwned> Cow<'_, B>

Source

pub const fn is_borrowed(c: &Self) -> bool

๐Ÿ”ฌThis is a nightly-only experimental API. (cow_is_borrowed #65143)

Returns true if the data is borrowed, i.e. if to_mut would require additional work.

Note: this is an associated function, which means that you have to call it as Cow::is_borrowed(&c) instead of c.is_borrowed(). This is so that there is no conflict with a method on the inner type.

ยงExamples
#![feature(cow_is_borrowed)]
use std::borrow::Cow;

let cow = Cow::Borrowed("moo");
assert!(Cow::is_borrowed(&cow));

let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
assert!(!Cow::is_borrowed(&bull));
Source

pub const fn is_owned(c: &Self) -> bool

๐Ÿ”ฌThis is a nightly-only experimental API. (cow_is_borrowed #65143)

Returns true if the data is owned, i.e. if to_mut would be a no-op.

Note: this is an associated function, which means that you have to call it as Cow::is_owned(&c) instead of c.is_owned(). This is so that there is no conflict with a method on the inner type.

ยงExamples
#![feature(cow_is_borrowed)]
use std::borrow::Cow;

let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
assert!(Cow::is_owned(&cow));

let bull = Cow::Borrowed("...moo?");
assert!(!Cow::is_owned(&bull));
1.0.0 ยท Source

pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned

Acquires a mutable reference to the owned form of the data.

Clones the data if it is not already owned.

ยงExamples
use std::borrow::Cow;

let mut cow = Cow::Borrowed("foo");
cow.to_mut().make_ascii_uppercase();

assert_eq!(
  cow,
  Cow::Owned(String::from("FOO")) as Cow<'_, str>
);
1.0.0 ยท Source

pub fn into_owned(self) -> <B as ToOwned>::Owned

Extracts the owned data.

Clones the data if it is not already owned.

ยงExamples

Calling into_owned on a Cow::Borrowed returns a clone of the borrowed data:

use std::borrow::Cow;

let s = "Hello world!";
let cow = Cow::Borrowed(s);

assert_eq!(
  cow.into_owned(),
  String::from(s)
);

Calling into_owned on a Cow::Owned returns the owned data. The data is moved out of the Cow without being cloned.

use std::borrow::Cow;

let s = "Hello world!";
let cow: Cow<'_, str> = Cow::Owned(String::from(s));

assert_eq!(
  cow.into_owned(),
  String::from(s)
);

Trait Implementationsยง

1.14.0 ยท Sourceยง

impl<'a> Add for Cow<'a, str>

Sourceยง

type Output = Cow<'a, str>

The resulting type after applying the + operator.
Sourceยง

fn add(self, rhs: Cow<'a, str>) -> Self::Output

Performs the + operation. Read more
1.14.0 ยท Sourceยง

impl<'a> Add<&'a str> for Cow<'a, str>

Sourceยง

type Output = Cow<'a, str>

The resulting type after applying the + operator.
Sourceยง

fn add(self, rhs: &'a str) -> Self::Output

Performs the + operation. Read more
1.14.0 ยท Sourceยง

impl<'a> AddAssign for Cow<'a, str>

Sourceยง

fn add_assign(&mut self, rhs: Cow<'a, str>)

Performs the += operation. Read more
1.14.0 ยท Sourceยง

impl<'a> AddAssign<&'a str> for Cow<'a, str>

Sourceยง

fn add_assign(&mut self, rhs: &'a str)

Performs the += operation. Read more
1.0.0 ยท Sourceยง

impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T>

Sourceยง

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
1.0.0 ยท Sourceยง

impl<'a, B: ?Sized + ToOwned> Borrow<B> for Cow<'a, B>

Sourceยง

fn borrow(&self) -> &B

Immutably borrows from an owned value. Read more
1.0.0 ยท Sourceยง

impl<B: ?Sized + ToOwned> Clone for Cow<'_, B>

Sourceยง

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
Sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
1.0.0 ยท Sourceยง

impl<B> Debug for Cow<'_, B>
where B: Debug + ToOwned<Owned: Debug> + ?Sized,

Sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
1.11.0 ยท Sourceยง

impl<B> Default for Cow<'_, B>
where B: ToOwned<Owned: Default> + ?Sized,

Sourceยง

fn default() -> Self

Creates an owned Cow<โ€™a, B> with the default value for the contained owned value.

1.0.0 ยท Sourceยง

impl<B: ?Sized + ToOwned> Deref for Cow<'_, B>

Sourceยง

type Target = B

The resulting type after dereferencing.
Sourceยง

fn deref(&self) -> &B

Dereferences the value.
Sourceยง

impl<T: Clone> DerefPure for Cow<'_, T>

Sourceยง

impl DerefPure for Cow<'_, str>

Sourceยง

impl<T: Clone>