String Versus Borrowed Str
Choose owned String or borrowed &str deliberately at function boundaries so allocations happen only where data genuinely changes.
Code
fn shout(text: &str) -> String {
// 借用入参:只读,零拷贝进入
text.to_uppercase()
}
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let owned = String::from("deploy notes");
// &String 自动解引用为 &str:借 owned,不复制
let loud = shout(&owned);
println!("{} -> {}", owned, loud);
// 返回借用:生命周期标注保证不悬垂
let a = "first candidate";
let b = "second";
println!("longer: {}", longest(a, b));
// 拼接需要 owned:to_string()/format! 显式分配
let combined = format!("{} + {}", a, b);
println!("{}", combined);
}How the snippet works
String Versus Borrowed Str is built around the functions shout, longest and main.
Applying it
Signature: fn shout(text: &str) -> String
The demo output is labeled (longer:), so every printed line maps back to its originating operation.
Launch the file; main takes over and steps through shout and longest.
Statements that matter
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn shout(text: &str) -> String {
// 借用入参:只读,零拷贝进入
text.to_uppercase()
}
Interactive Tools for This Topic
FAQ
- What does String Versus Borrowed Str print when run?
- Run it as a complete program — the output lines carry labels such as `longer:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.