I don't understand why the first code compile and the second do not compile.
What is the lifetime of the string slice str2 in the first code? Is it static ? I come from C++ and for me this should push the str on the stack no?
The first code:
fn compile()
{
let str1 = "abcd";
{
let str2 = "xyz";
let result = longest(str1, str2);
println!("The longest string is {}", result);
}
}
The second code:
fn not_compile()
{
let str1 = "abcd";
let result;
{
let str2 = String::from("xyz");
result = longest(str1, &str2);
}
println!("The longest string is {}", result);
}
The str literals like "..." will be references to static data in the binary. That data does not get copied to the stack, just referred in place. This is also true of C and C++ string literals -- their char* points to static data.
The String will be allocated on the heap, and has a non-static lifetime as a result.
There is also the arraystring crate for fixed capacity strings that provide a String-like interface, and smallstr which provides a form of String that dynamically chooses either the stack or the heap based on length.