4

I know that you can call something like:

rustc -Z unstable-options --pretty=expanded

to see the macro expansion, is there something similar to show the lifetimes of the variables in the file/crate?

I saw there is a pretty=typed, but it doesn't show the lifetimes as much as it shows what the type of everything is.

I could see an option to show lifetimes being really helpful for new Rust programmers (like me).

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
sbditto85
  • 1,485
  • 14
  • 21

1 Answers1

6

Lifetimes have a fancy name, but really they aren't super special. In fact, your source code already shows the lifetimes!

fn example() {
    let v1 = Vec::new();

    {
        let v2 = Vec::new();
    } // v2 goes out of scope here

} // v1 goes out of scope here

The lifetime of an item is basically just the braces in the source code where the variable is valid. There's a little bit of extra complexity when you have two items, but it's a straightforward extension:

fn example() {
    let v1 = Vec::new();  // | Lifetime of v1  
    let v2 = Vec::new();  // |                 | Lifetime of v2
}

In this example, v1 lives a bit longer than v2, which is only really important if you tried to refer to one in the other:

fn example() {
    let mut v1 = vec![];    // | Lifetime of v1  
    let mut v2 = vec![()];  // |                | Lifetime of v2
    v1.push(&v2);           // |                |
}

Here, v2 will be dropped before v1 (there's a LIFO ordering to the drops), and so the reference to v2 would be invalid between when v2 is dropped and v1 is dropped.

If you are more curious about how generic lifetime parameters interact, I'd recommend checking out this answer.

Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • I feel that the simplest cases are just as you described, but that there are other cases where you don't know why something isn't working and it would be great to see what the compiler thinks the lifetimes are. Somethings that are fuzzy to me are: what happens when something is cloned? is it all curl braces? what about inside a match block? is there a way to reference the parent lifetime? what about structs/functions with custom lifetimes? etc. So i understand the simple case, really want to make sure I see what the compiler thinks in the more complex case. – sbditto85 May 26 '15 at 17:51
  • Marking answer correct as it appears that at this time there isn't any way to have the compiler spit out lifetimes and in most cases it seems unnecessary. Thanks for the answer! – sbditto85 May 26 '15 at 18:38