0

So supposed I have this function:

fn longest(x: &str) -> &str {
    x
}

This will run fine if I call it.

However, if I do this:

fn longest(x: &str, y: &str) -> &str {
    x
}

I get the error

error[E0106]: missing lifetime specifier
 --> src/main.rs:1:33
  |
1 | fn longest(x: &str, y: &str) -> &str {
  |               ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
  |
1 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
  |           ++++     ++          ++          ++

Why is that? Shouldn't rust know that the return is x so the lifetime will follow x?

jlcv
  • 1,688
  • 5
  • 21
  • 50
  • Also: [nomicon](https://doc.rust-lang.org/nomicon/lifetime-elision.html) and [reference](https://doc.rust-lang.org/reference/lifetime-elision.html) – PitaJ Apr 12 '23 at 22:39
  • 2
    Rust will never infer the type of a function based on its body. That would be very fragile, because changing the body of a function could break completely unrelated code. Types are the skeleton that everything else is built around - Rust will infer the types of values, but never the structure of a type or function itself. – Peter Hall Apr 12 '23 at 22:53
  • Thanks everyone, that was super helpful and it makes sense now. One thing Id on't get is that why do `struct`s need to have their lifetime specified. Why can't it be done automatically, for example ``` struct ImportantExcerpt<'a> { part: &'a str, } ``` Isn't it obvious here that the struct should have the same lifetime as the only field in it? – jlcv Apr 12 '23 at 23:17
  • @jlcv Just like you may need to specify a lifetime when required for `&str`, you may also need to specify it on the type `ImportantExcerpt<'a>`. If there were no generic on the type definition, that would seem a bit weird. And even when not specified, it is recommended that the lifetime be explicitly elided `ImportantExcerpt<'_>` since it can result in very confusing errors if a type has a lifetime bound that you were unaware of. – kmdreko Apr 13 '23 at 00:22

0 Answers0