On this page
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
- Clone-on-Write (
Borrowed(&T)vs.Owned(T::Owned)): Avoids heap allocation on the fast path when no mutation is needed. - Call
.to_mut()to lazily clone only if you actually need to modify the data.
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
- tuts/rust/std/smart_pointers/RefCell Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/smart_pointers Linked here; links to this page; shared tags: #prog, #rust, #stdlib
- tuts/rust/std/sync Linked here; shared tags: #prog, #rust, #stdlib
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/VecDeque shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Display shared tags: #prog, #rust, #stdlib, #tier