You can tell Rust that the result is alive only as long as the arguments singular and plural are alive:
fn pluralize<'a>(singular: &'a str, plural: &'a str, count: u64) -> &'a str {
// ...
}
Note that this prevents you from doing something like this:
let singular = "one".to_string();
let pluralized = {
let plural = "two".to_string();
pluralize(&singular, &plural, 1)
};
println!("{:?}", pluralized);
That is, even though pluralized would be a reference to singular, which lives long enough to be printed in the end, Rust assumes it could also be a reference to plural, which goes out of scope before the final print statement. The compiler thus tells you:
error[E0597]: `plural` does not live long enough
--> test.rs:9:30
|
7 | let pluralized = {
| ---------- borrow later stored here
8 | let plural = "two".to_string();
9 | pluralize(&singular, &plural, 1)
| ^^^^^^^ borrowed value does not live long enough
10 | };
| - `plural` dropped here while still borrowed
In general, Rust normally requires an explicit lifetime for argument and return types of functions:
fn do_nothing<'a>(s: &'a str) -> &'a str { ... }
This means do_nothing is a function that takes an argument with lifetime 'a and returns a reference with the same lifetime 'a. But the compiler implements some sensible rules to guess the lifetimes of the result type in most common cases. This allows you to omit the lifetimes for argument and result types, like this:
fn do_nothing(s: &str) -> &str { ... }
The rules are:
- Each elided lifetime in the parameters becomes a distinct lifetime parameter.
- If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to all elided output lifetimes.
- If the receiver has type &Self or &mut Self, then the lifetime of that reference to Self is assigned to all elided output lifetime parameters.
(from https://doc.rust-lang.org/stable/reference/lifetime-elision.html)
In your example, you had two lifetimes in the arguments (one for each &str reference). None of the rules matched, so the compiler asked you to specify the lifetimes explicitly.