0
votes

I have been experimenting on Rust for quite some time. There is a confusion regarding the lifetimes in Rust.Have a look in the code below:

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

    result = longest(string1.as_str(),string2);

    }
    println!("The Longest String is {}",result);
}

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

The string2 lifetime ends after the inner scope, and result is defined in the outer scope.When passing result in println!, the compile does not complain, and goes ahead and prints the result. However when I change the string2 to be like:

let string2 = String::from("xyzvd");

The borrow checker will complain. Why is that happening.

1

1 Answers

2
votes

The type for a string literal ”xyzvn” is &'static str which means it lives as long as the program does. But when you create a new string based on it its lifetime ends at the end of the block and it cannot be used outside.

For more information see the documentation on static lifetime