Lifetime example for the book

Hello everyone,

I'm reading the rust book, and i'm asking myself why this code compile

// I toy version from my mind where i expected the same issue than the original one 
use std::env;

fn main() {
  let mut args = env::args();
  let s1 = args.nth(1).unwrap();
  let s2 = args.nth(0).unwrap();

  let result = {
    let r1 = s1.as_str();
    let r2 = s2.as_str();
    if r1.len() > r2.len() {
      r1
    } else {
      r2
    }
  };
  println!("the longest is {}", result)
}

whereas this one fail

// Original code from the rust book
fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";

    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}

To be more precise, I've tried to simply replace the function call by a block of code and i was expecting the same result (my rewriting should've failed too).

Thanks

PS : Example come from here
https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html

1 Like

Example from the book does not compile only because the function signature of longest is invalid. By inlining the function, you effectively removed the only invalid part of code.

3 Likes

and this happens because the borrow checker automatically guesses all lifetimes inside functions, but not across function boundaries. This is intentional, because functions are supposed to be an abstraction layer that hides their implementation details.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.