Created
March 12, 2020 14:59
-
-
Save platy/0c387a3eadd77a7ea1e9d509667a95a3 to your computer and use it in GitHub Desktop.
I was confused that the string slice retrieved from the struct was not allowed to outlive it. It was because I had put the same lifetime bound on the borrow of self as on the contained string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
println!("{}", get_back_the_same_string("Hello World!")); | |
} | |
fn get_back_the_same_string<'a>(string: &'a str) -> &'a str { | |
let nt = NewType(string); | |
return nt.get_string() | |
} | |
struct NewType<'b>(&'b str); | |
impl <'b> NewType<'b> { | |
fn get_string(&'b self) -> &'b str { | |
// ^^ this lifetime caused the problem, I guess it prevents 'b from outliving self | |
return &self.0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment