Avatar ·

Why in Rust you need to explicitly specify lifetimes, and how do they work?

I'm new to Rust and trying to understand the concept of lifetimes. I wrote a simple function that returns a reference to an array element: ```rust fn get_first_element(arr: &[i32]) -> &i32 { &arr[0] } ``` The compiler compiled this without any issues. But when I tried to write a function that takes two references and returns one of them: ```rust fn longest(x: &str, y: &str) -> &str { if x.len() > y.len() { x } else { y } } ``` I got an error: "missing lifetime specifier". Why did the compiler figure it out on its own in the first case, but requires explicit lifetime specification in the second? I thought Rust was smart and could infer everything automatically. I understand that lifetimes are needed to prevent dangling references, but I don't understand the logic behind when they are