Skip to content

Instantly share code, notes, and snippets.

@kscz
Last active April 4, 2016 22:33
Show Gist options
  • Save kscz/76a31c068daea8341b4812d56515bd65 to your computer and use it in GitHub Desktop.
Save kscz/76a31c068daea8341b4812d56515bd65 to your computer and use it in GitHub Desktop.

What's this?

This is a follow-up to my silly simple rust tutorial. Basically, there's a lot of weird edgecases with lifetimes, and I wanted to avoid cluttering up the main part of the tutorial.

Lifetime, why are you such a boring network?

Alright, let's get right into it:

YOU GUESSED WRONG! IN PROGRESS

We can show ways that this guess can be wrong! Let's make the first example from this section a little different:

fn electric_slide() -> &'static str {
  let x = String::from("It's electric! ");
  print_and_return_reference(&x)
}

// ERROR: We didn't specify the lifetime of the return, and it doesn't match rust's guess!
fn print_and_return_reference(print_me: &str) -> &str {
  print!("{}", print_me);
  &"Boogie woogie woogie!"
}

fn main() {
  let x = electric_slide();
  println!("{}", x);
}

Alright, so this is a little more complicated than I wanted the example to be, but it shows what I want. Rust returns the following error message for the above code:

:8:31: 8:32 error: `x` does not live long enough
:8   print_and_return_reference(&x)

Which I'll

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment