In the newest version of Rust Compiler, the Lifetime Elision can only inference the lifetime annotations in specific circumstances. For example, if I have a function:
fn get_match_sub_vec(tar_vec: &Vec<&Vec<i32>>, given_vec: &Vec<i32>) -> Option<&Vec<i32>> {
for v in tar_vec.iter() {
if v.len() == given_vec.len() {
return Some(v);
}
}
return None;
}
The compiler will throw the error: missing lifetime specifier.
However, if I inproperly annotate the lifetime of parameters:
fn get_match_sub_vec<'a,'b>(tar_vec: &'a Vec<&Vec<i32>>, given_vec: &'b Vec<i32>) -> Option<&'b Vec<i32>> {
for v in tar_vec.iter() {
if v.len() == given_vec.len() {
return Some(v);
}
}
return None;
}
The compiler will throw the error: explicit lifetime required in the type of tar_vec
, which means the lifetime of the returned value is mismatch the annotation in the function signature.
My question is: If the Rust compiler is able to detect usage of reference and check the correctness of lifetime annotation, why do we still need to explicitly add the lifetime annotation on the function signature?
The only reason I guess is to avoid confusion of references lifetimes during the usage of traits. If my guess is right, why don't the Rust compiler only check the lifetime annotation on traits instead of on functions?
Could anyone answer my question? Thanks so much!