Lifetime: why doesn't Rust complain about this?

I just started learning Rust and reading through The Rust Programming Language book online.

I'm a bit puzzled with the following code dealing with the lifetime (similar to the example in Listing 10-24):

fn main() {
  let s1 = String::from("hi");
  let result;
    let s2 = "hello";
    result = longest(s1.as_str(), &s2);
  println!("The longest string is '{}'", result);

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
  if x.len() > y.len() {
  } else {

I was expecting the compiler to error out because s2 went out of scope by the time result was printed. Since 'a refers to the smaller of the lifetime of the references passed in, the returned value of longest() should not be able to live outside of the inner block, right? So what am I missing?

Thanks in advance!

Hi, s2 in your example is embedded in your executable and is of type &'static str. Even when s2 goes out of scope the str isn't destroyed.

The compiler can show you the type if you try to assign the wrong one (on purpose):

let s2: () = "hello";
expected type `()`
found type `&'static str`

Which makes the lifetime of &s1 the shortest, so no error. If you change the type of s2 to String, you will get an error. playground


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.