Choose &str for borrowing, String for ownership, and Cow for conditional mutation to optimize Rust string performance.
Use &str for read-only references, String for owned mutable text, and Cow<'a, str> when you might need to mutate borrowed data without always allocating.
use std::borrow::Cow;
fn process(s: &str) -> Cow<'_, str> {
if s.contains(" ") {
Cow::Owned(s.to_uppercase())
} else {
Cow::Borrowed(s)
}
}
Think of &str as a view of text you don't own, String as a text box you own and can change, and Cow as a smart wrapper that borrows the text if you don't need to change it but buys a copy if you do. This saves memory by avoiding unnecessary copies when you only need to read the data.