Cow (Clone-on-Write)
Cow<'a, T> is either borrowed &'a T or owned T - clones on write when mutation required.
Busca en todas las páginas de la documentación
Cow<'a, T> is either borrowed &'a T or owned T - clones on write when mutation required.
use std::borrow::Cow;
fn maybe_upper(s: Cow<str>) -> Cow<str> {
if s.contains("urgent") {
Cow::Owned(s.to_uppercase())
} else {
s
}
}When to reach for this: APIs accepting &str or String and sometimes needing owned mutation.
use std::borrow::Cow;
fn append_suffix<'a>(s: Cow<'a, str>, suffix: &str) -> Cow<'a, str> {
if suffix.is_empty() { return s; }
let mut owned = s.into_owned();
owned.push_str(suffix);
Cow::Owned(owned)
}
fn main() {
let borrowed = Cow::Borrowed("hello");
let owned = append_suffix(borrowed, "!");
println!("{owned}");
}What this demonstrates:
into_owned converts borrow to owned copy if neededCow avoids forcing caller to allocateCow<str>, Cow<[u8]>, Cow<OsStr> common. Implements Deref to target.
String upfront.Cow may need 'static owned branch.String/&str overloads. Fix: impl AsRef<str> simpler sometimes.String in stored structs often.| Alternative | Use When | Don't Use When |
|---|---|---|
&str + String overloads | Two clear APIs | Many combo APIs |
Arc<str> | Shared immutable | Single-owner mutation |
Always String | Simple | Hot path borrow |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026