Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Smart Pointers and Memory

Rust Cow<'a, B> type

Reference for Rust Cow<'a, B>: Borrowed and Owned variants, to_mut, into_owned, Cow<str> and Cow<[T]>, and returning borrowed data when nothing changes.

Cow<'a, B> ("clone on write") is an enum that holds either a borrowed &'a B or an owned <B as ToOwned>::Owned value. It lets a function return borrowed data in the common case and allocate only when it really has to change something.

The usual instances are Cow<'a, str> (borrowed &str or owned String) and Cow<'a, [T]> (borrowed slice or Vec<T>). Cow implements Deref<Target = B>, so you can read through it exactly as you would the borrowed form.

Rust
use std::borrow::Cow;

let borrowed: Cow<str> = Cow::Borrowed("text");
let owned: Cow<str> = Cow::Owned(String::from("text"));

Try it

Rust Allocate only when needed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust to_mut and into_owned

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub enum Cow<'a, B: ?Sized + 'a>
where
    B: ToOwned,
{
    Borrowed(&'a B),
    Owned(<B as ToOwned>::Owned),
}

impl<B: ?Sized + ToOwned> Cow<'_, B> {
    pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned;
    pub fn into_owned(self) -> <B as ToOwned>::Owned;
}
Item Description
Cow::Borrowed(r) Wraps a reference; no allocation.
Cow::Owned(v) Wraps an owned String/Vec/etc.
to_mut() Returns &mut to the owned value, converting a Borrowed into Owned first (clone) if necessary.
into_owned() Consumes the Cow, cloning only if it was borrowed.
From impls &str and String convert to Cow<str>; &[T] and Vec<T> to Cow<[T]>.

Edge cases. to_mut never clones twice: after the first call the value is Owned. matches!(cow, Cow::Owned(_)) is the stable way to ask which variant you have. The + operator and += work on Cow<str> with a &str on the right.

Usage notes

  • Return Cow<'_, str> from functions that usually pass text through unchanged (escaping, trimming, normalizing): the fast path costs nothing.
  • Accept impl Into<Cow<'a, str>> in constructors to take either &'static str or String without forcing a clone.
  • The lifetime ties the Cow to the borrowed source, so a Cow<'a, str> cannot outlive the &'a str it may point to. For storage use Cow<'static, str>, as error types often do.
  • Cow<str> equals &str and String with ==, and prints with {} directly.
  • String::from_utf8_lossy is a standard-library function that returns Cow<str>: borrowed if the bytes were valid UTF-8, owned if replacements were needed.
  • Do not reach for Cow when you always allocate or never allocate; a plain String or &str is simpler.