Skip to content

Instantly share code, notes, and snippets.

@platy
Created March 12, 2020 14:59
Show Gist options
  • Save platy/0c387a3eadd77a7ea1e9d509667a95a3 to your computer and use it in GitHub Desktop.
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
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