Why does Rust need humans to tell it how long a variable’s lifetime is?
I understand the lifetimes concept but I do not understand why Rust can’t work out lifetimes itself during compile time and needs humans to spell it out?
For example, in https://doc.rust-lang.org/book/ch12-04-testing-the-librarys-functionality.html
‘’’
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
vec![]
}
‘’’
Rust can’t possibly know which of the two arguments we need, so we need to tell it explicitly. Because contents is the argument that contains all of our text and we want to return the parts of that text that match, we know contents is the argument that should be connected to the return value using the lifetime syntax.
Is it not obvious when a string slice comes from inside another string slice? If a human can figure it out based on just the given input? Why can’t Rust?
Edit 1: A follow up question, after looking at some of the answers. Why is needing to specify lifetimes unique to Rust? Is it related to Rust using an ownership model instead of garbage collection like other languages?