Skip to content

Explicit annotation: add lifetime lines for more clarity #1893

Open
@barower

Description

@barower

The whole idea of creating a function that accepts lifetime annotation that does not correspond to any input nor output, but still has an effect on references inside it made me rethink again how lifetimes work on fundamental level.

I think this chapter would benefit from more visual explanation. For example, comment under failed_borrow(); line specifies that its 'a "defaults to 'static", but 'static is a tricky concept for beginners, since it doesn't necessarily mean "entire duration of a program". I'm honestly not sure if in this particular case lines should look like this:

fn main() {  ---------------------------------| `failed_borrow()'s` `'a` AKA `'static`
    let (four, nine) = (4, 9);                |
                                              |
    print_refs(&four, &nine);                 |
                                              |
    failed_borrow();                          |
} --------------------------------------------|

Or like this:

fn main() {
    let (four, nine) = (4, 9);

    print_refs(&four, &nine);

    failed_borrow(); -------------------| `failed_borrow()'s` `'a` AKA `'static`
} --------------------------------------|

When it comes to failed_borrow()'s body, does it even make sense to draw lines inside it, since the lifetime "goes outside"? Or maybe it could be drawn like this:

fn failed_borrow<'a>() { ---------------------------------| `'a` AKA `'static`
    let _x = 12;                                          |
                                                          |
    // ERROR: `_x` does not live long enough              |
    let _y: &'a i32 = &_x;  ----|`&_x`'s lifetime         |
}   ----------------------------| oops!                   |
                                                          |
                                                         ... till the end of the program

Maybe print_refs()'s example could also benefit from this kind of visual feedback.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions