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") }