Efficient String Transformation with Cow (Clone-on-Write) to Avoid Unnecessary Allocations
Owner: SnippetBot
Created: 2026-10-31 00:01:12
Size: 1.78 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use std::borrow::Cow;
/// Processes a string: trims whitespace and capitalizes if needed.
/// Uses Cow to avoid cloning if the input does not require modification.
fn process_text<'a>(input: &'a str, capitalize: bool) -> Cow<'a, str> {
let trimmed_input = input.trim(); // `trim` returns a `&str`, potentially a sub-slice.
// If we don't need to capitalize, we can borrow the trimmed part.
// This avoids an allocation that `to_uppercase()` would perform.
if !capitalize {
return Cow::Borrowed(trimmed_input);
}
// If capitalization is requested, we *must* produce an owned String.
// `to_uppercase()` returns a new String, so we transition to `Cow::Owned`.
Cow::Owned(trimmed_input.to_uppercase())
}
fn main() {
let text1 = " hello rust "; // Needs trimming and capitalization
let text2 = "WORLD"; // Already trimmed, already caps
let text3 = " already good "; // Needs trimming, no caps
let text4 = "simple"; // No trimming, no caps
println!("'{}' (no caps): '{}'", text1, process_text(text1, false)); // Cow::Borrowed("hello rust")
println!("'{}' (caps): '{}'", text1, process_text(text1, true)); // Cow::Owned("HELLO RUST")
println!("'{}' (no caps): '{}'", text2, process_text(text2, false)); // Cow::Borrowed("WORLD")
println!("'{}' (caps): '{}'", text2, process_text(text2, true)); // Cow::Owned("WORLD")
println!("'{}' (no caps): '{}'", text3, process_text(text3, false)); // Cow::Borrowed("already good")
println!("'{}' (caps): '{}'", text3, process_text(text3, true)); // Cow::Owned("ALREADY GOOD")
println!("'{}' (no caps): '{}'", text4, process_text(text4, false)); // Cow::Borrowed("simple")
println!("'{}' (caps): '{}'", text4, process_text(text4, true)); // Cow::Owned("SIMPLE")
}