Reputation: 121
take the code from rustbook for example
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
we have the above function, now suppose we have main:
// can't compile , i understand this part, just post here for reference
fn main1(){
let string1 = String::from("abcd");
let result;
{
let string2 = String::from("xyz"); // we will change this to &str in next example
result = longest(string1.as_str(), string2.as_str());
^^^^^^ doesn't compile , string2 doesn't live long enough
}
println!("The longest string is {}", result);
}
but if we slight change it to the code below, changing the string2 to be a string slice, this code actually compiles , and i dont quite know what's going on, does the "xyz" still count as valid memory?
//This compiles. but why? shouldn't ```longest()``` return a smaller lifetime and refuses to compile?
fn main2(){
let string1 = String::from("abcd");
let result;
{
let string2 = "xyz"; // <------ changed
result = longest(string1.as_str(), string2);
}
println!("The longest string is {}", result);
}
Upvotes: 0
Views: 76
Reputation: 998
string2
will always be dropped, but in first example string2
owns your data, in second it’s just a reference to ’static
data, so the data won’t be invalidated after string2
’s drop.
Upvotes: 1
Reputation: 799
The lifetime of a string literal is 'static
(the complete type is &'static str
), which means it will live until the end of the program. That's because strings are put as data into a special section of the compiled binary, so as long as the program is running, that data is also accessible.
Upvotes: 1
Reputation: 70860
"xyz"
is &'static str
, it is valid for the entire duration of the program.
Upvotes: 1