Skip to content

Consider re-tuning the lifetime elision rules for trait objects #91302

Open
@scottmcm

Description

@scottmcm

The lifetime elision rules for functions are willing to fail sometimes, and that's good because -> &i32 defaulting to -> &'static i32 would not be what people generally want, and having the error say "hey, what lifetime did you mean?" is way better than getting borrowck errors about "that's not 'static".

It might be worth taking inspiration from that to improve the elision rules for dyn Trait, as lints for now and possibly as hard changes in a future edition.

For example, impl dyn Trait is currently impl dyn Trait + 'static, but it's not clear that's good. It might be better to require that the user write impl dyn Trait + '_ or impl dyn Trait + 'static to say which they want. Inspired by this thread: https://users.rust-lang.org/t/why-do-associated-functions-in-impl-dyn-trait-require-static-lifetime/67548/2?u=scottmcm

Similarly, the + 'static default applies even inside a struct with a lifetime. For example, #91292 had

pub struct SectionMut<'a> {
    data: &'a mut Option<Box<dyn SectionData>>,
}

where the implicit + 'static is more restrictive than needed because it's behind the &'a -- but being in the Box hides that from elision.

I don't have any concrete proposal here right now, but I figured I'd open this as a place to track it.


Other examples (feel free to edit this post to add more down here):

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-dyn-traitArea: trait objects, vtable layoutA-lifetimesArea: Lifetimes / regionsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.A-maybe-future-editionSomething we may consider for a future edition.C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language team

    Type

    No type

    Projects

    Status

    Needs help: Design

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions