Cow: borrow until you must own in Rust
Clone-on-write returns a borrow when nothing changed and an owned value when it did.
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input)
}
}
fn main() {
for raw in ["already_clean", "needs a change"] {
let out = normalize(raw);
let owned = matches!(out, Cow::Owned(_));
println!("{out} (allocated: {owned})");
}
println!("{}", normalize("plain").len());
}
How it works
Cow::Borrowedcosts nothing;Cow::Ownedallocates.- The caller treats both the same through deref.
- It suits normalizing functions that usually change nothing.
Keywords and builtins used here
Cowelsefnforifinletmainnormalizestruse
The run, in numbers
- Lines
- 18
- Characters to type
- 373
- Tokens
- 123
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 70 seconds.
Step 1 of 2 in Borrowing without copying, step 5 of 11 in Lifetimes & interior mutability.