On this page
  1. Cow
  2. Signature & Overview
  3. Notes & Pitfalls
  4. Example

Cow

Prev: `RefCell` | Up: smart_pointers | Next: sync
Rel: smart_pointers, rust/builtins
Ref: Rust std — Cow
Tags: #public #prog #rust #stdlib #smart_pointers #tier/specialized


Signature & Overview

Cow<'a, B>  /* Borrowed(&'a B) | Owned(B::Owned) */

Clone-on-Write smart pointer avoiding heap allocation unless mutation is actually needed.

Notes & Pitfalls

Example

use std::borrow::Cow;

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

fn main() {
    assert!(matches!(normalize("clean"), Cow::Borrowed("clean")));
    assert_eq!(normalize("has space"), "has_space");
}

Linked from

Related notes