Lifetime Elision In Function Signatures
Apply the elision rules that let one-input functions and methods omit lifetimes, and see why picking one of two borrows still needs an explicit lifetime.
Code
// 单个入参、返回借用:输出生命周期唯一,可以省略标注
fn first_word(text: &str) -> &str {
text.split_whitespace().next().unwrap_or("")
}
// 两个来源、返回借用:编译器无从判断该跟谁一致,必须显式标注
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
struct Line<'a> {
text: &'a str,
}
impl<'a> Line<'a> {
// 方法:省略时 &self 的生命周期自动分配给返回的借用
fn prefix(&self, n: usize) -> &str {
&self.text[..n.min(self.text.len())]
}
}
fn main() {
let owned = String::from("deploy the new build");
let head = first_word(&owned);
println!("first word: {head}");
let left = "alpha";
let right = String::from("bravo");
println!("longer: {}", longer(left, &right));
let line = Line {
text: "eta=12ms status=ok",
};
println!("prefix: {}", line.prefix(7));
// head 借的是 owned:owned 还活着,借用才成立
println!("borrow still valid: {head} from {owned}");
}How it works
Lifetime Elision In Function Signatures comes down to the functions first_word, longer, prefix and main.
Points of care
- Runs with what the toolchain already gives you — nothing extra.
Putting it to use
Entry signature: fn first_word(text: &str) -> &str
Output lines are prefixed (first word:, longer:, prefix:), making each step’s effect easy to spot.
Execute the file and main walks through first_word, longer and prefix, in that order.
Core lines
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn prefix(&self, n: usize) -> &str {
&self.text[..n.min(self.text.len())]
}
fn first_word(text: &str) -> &str {
text.split_whitespace().next().unwrap_or("")
}
Interactive Tools for This Topic
FAQ
- What does Lifetime Elision In Function Signatures print when run?
- Invoke the file as-is — the `first word:`, `longer:`, `prefix:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.