I read the tutorial on the official website and I have some questions on the lifetime of constant strings / string literals.
I get an error when I write the following code:
fn get_str() -> &str {
"Hello World"
}
error:
error[E0106]: missing lifetime specifier
--> src/main.rs:1:17
|
1 | fn get_str() -> &str {
| ^ expected lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
= help: consider giving it a 'static lifetime
However it's OK when I add a parameter:
fn get_str(s: &str) -> &str {
"Hello World"
}
Why does this work? How does "Hello World"
borrow from the parameter s
, even it though it has nothing to do with s
?
A String Literal, also known as a string constant or constant string, is a string of characters enclosed in double quotes, such as "To err is human - To really foul things up requires a computer." String literals are stored in C as an array of chars, terminted by a null byte.
Strings are stored on the heap area in a separate memory location known as String Constant pool. String constant pool: It is a separate block of memory where all the String variables are held. String str1 = "Hello"; directly, then JVM creates a String object with the given value in a String constant pool.
The tricky thing is defining the return value type. Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string.
Lifetime elision infers that the full type of
fn get_str(s: &str) -> &str
is
fn get_str<'a>(s: &'a str) -> &'a str
which basically means that the return value of get_str
has to be valid as long as s
is valid. The actual type of the string literal "Hello world"
is &'static str
, which means that it is valid for the entire run of the program. Since this satisfies the lifetime constraints in the function signature (because 'static
always includes 'a
for any 'a
), this works.
However, a more sensible way to get your original code to work would be to add an explicit lifetime to the function type:
fn get_str() -> &'static str {
"Hello World"
}
How does "Hello World" borrow from the parameter
s
, even it has nothing to do withs
?
There are only two options that would make sense for the return value's lifetime in a function with a single reference argument:
'static
, as it should be in your example, orThere is some rationale for choosing the latter in the link at the top of this post, but it basically comes down to the fact that the latter is the far more common case. Note that lifetime elision does not look at the function body at all, it just goes by the function signature. That's why it won't take the fact that you're just returning a string constant into account.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With