While reading Chapter 12.4 of the Rust Book, I stumbled upon this function:
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
vec![]
}
I understand why the code doesn't compile without the explicit lifetime annotation for the contents
argument and the return value - the lifetime elision rules do not apply for functions with at least two borrowed arguments.
But I'm curious what's the implicit lifetime annotation for the query
argument. I could think of two scenarios:
// Scenario 1
pub fn search<'a>(query: &'a str, contents: &'a str) -> Vec<&'a str> {
vec![]
}
// Scenario 2
pub fn search<'a, 'b>(query: &'b str, contents: &'a str) -> Vec<&'a str> {
vec![]
}
Both scenarios compile, so query
gets either lifetime 'a
or 'b
. Which one is correct?
pub fn search<'a>(_query: &str, _contents: &str) -> Vec<&'a str>
But that's definitely an unusual situation. – Aaren