borrow

Cow, Borrow, and ToOwned: going from a borrowed view to an owned value, and why Cow is not a general way to skip copies.

The convert page already covers From, Into, TryFrom, AsRef, and AsMut. This page is the complementary trio in std::borrow: Borrow, ToOwned, and Cow. Borrow is the trait HashMap uses when you look up a String key with a &str. ToOwned is the inverse direction, from a borrowed view to an owned value, such as str to String or [T] to Vec<T>.

Cow<B> is copy-on-write in a narrow sense: it can hold either a borrow or an owned value of B::Owned. Calling to_mut on a Cow::Borrowed clones first. Cow is not a general switch that makes every API allocation-free. The Path page already mentions to_string_lossy, which returns Cow<str>. Examples were compiled with rustc 1.90.0 and --edition=2024.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
ToOwned::to_owned and Borrow::borrowCreate an owned value from a borrow, or borrow an owned value as its borrowed form.
Cow, to_mut, and into_ownedHold either a borrow or an owned value. to_mut clones when the Cow is still Borrowed.

ToOwned and Borrow

ToOwned::to_owned builds the owned counterpart of a borrowed type. For str, that is String. Borrow is implemented so that String can be borrowed as str, and Vec<T> as [T]. That is why a HashMap<String, V> can be queried with a &str: the key type and the lookup type must hash and compare equivalently. AsRef is a cheaper "view as" conversion and does not carry that Hash + Eq contract. Keep AsRef on the convert page.

ToOwned::to_owned and Borrow::borrow

pub trait ToOwned {
    type Owned: Borrow<Self>;
    fn to_owned(&self) -> Self::Owned;
}
pub trait Borrow<Borrowed>
    where
        Borrowed: ?Sized
{
    fn borrow(&self) -> &Borrowed;
}

Create an owned value from a borrow, or borrow an owned value as its borrowed form.

ParameterDescription
selfThe borrowed view for to_owned, or the owned value for borrow.

Returns: to_owned returns Owned (String for str, Vec<T> for [T]). borrow returns a shared reference to the borrowed type.

  • to_owned on str allocates a new String. It is not a way to avoid a copy; it is how you take ownership of a copy.
  • HashMap lookup with borrowed keys is documented on the HashMap page. This page only shows the traits that make that lookup possible.
rust
use std::borrow::{Borrow, ToOwned};

fn main() {
    let borrowed: &str = "port";
    let owned: String = borrowed.to_owned();
    let as_str: &str = owned.borrow();
    println!("borrowed_key={as_str}");
}

Expected output

borrowed_key=port

Related: From, Into, AsRef, and AsMut, HashMap key lookup, str and String

Official documentation →

Cow: borrow until you have to own

Cow is an enum with Borrowed and Owned variants. A function can return Cow::Borrowed when the input already has the form you need, and Cow::Owned only when it has to allocate a new value. That is borrow-to-owned, not a promise that nothing will ever be copied.

to_mut returns &mut B::Owned. If the Cow is already Owned, it mutates in place. If it is Borrowed, to_mut clones into an owned value first, then returns a mutable reference. into_owned likewise clones if the value was borrowed.

Cow, to_mut, and into_owned

pub enum Cow<'a, B>
    where
        B: 'a + ToOwned + ?Sized
{
    Borrowed(&'a B),
    Owned(<B as ToOwned>::Owned),
}
pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned
pub fn into_owned(self) -> <B as ToOwned>::Owned

Hold either a borrow or an owned value. to_mut clones when the Cow is still Borrowed.

ParameterDescription
selfA Cow that may be Borrowed or Owned. to_mut takes &mut self. into_owned consumes self.

Returns: to_mut yields a mutable reference to the owned form, cloning first if needed. into_owned returns that owned form by value.

  • label returns Cow::Borrowed("host") unchanged, and Cow::Owned("host_name") only after replace allocates a String.
  • to_mut on Cow::Borrowed("ok") clones into a String, then make_ascii_uppercase mutates that buffer. The clone is real work, not a free conversion.
  • Path::to_string_lossy returning Cow<str> is shown on the Path page.
rust
use std::borrow::Cow;

fn label(raw: &str) -> Cow<'_, str> {
    if raw.contains(' ') {
        Cow::Owned(raw.replace(' ', "_"))
    } else {
        Cow::Borrowed(raw)
    }
}

fn main() {
    match label("host") {
        Cow::Borrowed(value) => println!("borrowed={value}"),
        Cow::Owned(_) => println!("unexpected owned"),
    }
    match label("host name") {
        Cow::Borrowed(_) => println!("unexpected borrowed"),
        Cow::Owned(value) => println!("owned={value}"),
    }

    let mut cow: Cow<str> = Cow::Borrowed("ok");
    cow.to_mut().make_ascii_uppercase();
    println!("to_mut={cow}");
}

Expected output

borrowed=host
owned=host_name
to_mut=OK

Related: Path::to_string_lossy, Official Cow

Official documentation →