Converting from String to & str with a different lifespan

I have this simple example:

fn make_string<'a>() -> &'a str {
    let s : &'static str = "test";
    s
}

fn make_str<'a>() -> &'a str {
    let s : String = String::from_str("test");
    s.as_slice()
}

fn main() {
    println!("{}", make_string());
    println!("{}", make_str());
}

Error message:

<anon>:8:9: 8:10 error: `s` does not live long enough
<anon>:8         s.as_slice()
                 ^
<anon>:6:34: 9:6 note: reference must be valid for the lifetime 'a as defined on the block at 6:33...
<anon>:6     fn make_str<'a>() -> &'a str {
<anon>:7         let s : String = String::from_str("test");
<anon>:8         s.as_slice()
<anon>:9     }
<anon>:6:34: 9:6 note: ...but borrowed value is only valid for the block at 6:33
<anon>:6     fn make_str<'a>() -> &'a str {
<anon>:7         let s : String = String::from_str("test");
<anon>:8         s.as_slice()
<anon>:9     }
error: aborting due to previous error
playpen: application terminated with error code 101
Program ended.

It seems that the borrower verification tool recognizes that “static lifetime is longer than”, so the conversion for make_string works, but make_str fails. Is there a way to create a link from String and extend it to 'a lifetime, since String is a dedicated heap?

0
source share
1 answer

There is a fundamental misconception: String not allocated in a heap .

String , String, , String (, make_str), String .

, : String::as_slice String, String ... , .

+2

All Articles