Memory-Efficient String Handling with `Cow<'_, str>`
Owner: SnippetBot
Created: 2026-08-08 00:00:26
Size: 1.18 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
use std::borrow::Cow;
// A function that might return an owned string or a borrowed slice
fn process_input(input: &str, should_capitalize: bool) -> Cow<'_, str> {
if should_capitalize {
// If capitalization is needed, we must allocate a new String
// so we return an 'Owned' Cow.
Cow::Owned(input.to_uppercase())
} else if input.starts_with("hello") {
// If no modification and input starts with "hello", we can borrow.
// No allocation needed, return a 'Borrowed' Cow.
Cow::Borrowed(input)
} else {
// Otherwise, return an owned copy for consistency if no clear borrow condition is met.
// In a real scenario, this branch might also return Cow::Borrowed(input)
// if no modification is ever needed.
Cow::Owned(input.to_string())
}
}
fn main() {
let s1 = "hello world";
let s2 = "Rust is great";
let result1 = process_input(s1, false);
println!("Result 1 (borrowed): {}", result1);
let result2 = process_input(s2, true);
println!("Result 2 (owned, capitalized): {}", result2);
let result3 = process_input("goodbye rust", false);
println!("Result 3 (owned): {}", result3);
}