Skip to content

Using &T in where clause should suggest HRTB #105422

Open
@Swatinem

Description

@Swatinem

Given the following code:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0649baa344cf71ca09719ebebe1bf5d2

pub struct Foo;
pub struct Bar;

impl From<&Foo> for Bar {
    fn from(_: &Foo) -> Bar { Bar }
}

pub fn fails<E>(e: E) -> Bar where &E: Into<Bar> {
    (&e).into()
}

The current output is:

error[[E0637]](https://doc.rust-lang.org/stable/error-index.html#E0637): `&` without an explicit lifetime name cannot be used here
 --> src/lib.rs:8:36
  |
8 | pub fn fails<E>(e: E) -> Bar where &E: Into<Bar> {
  |                                    ^ explicit lifetime name needed here

error[[E0310]](https://doc.rust-lang.org/stable/error-index.html#E0310): the parameter type `E` may not live long enough
 --> src/lib.rs:8:40
  |
8 | pub fn fails<E>(e: E) -> Bar where &E: Into<Bar> {
  |                                        ^^^^^^^^^ ...so that the reference type `&'static E` does not outlive the data it points at
  |
help: consider adding an explicit lifetime bound...
  |
8 | pub fn fails<E: 'static>(e: E) -> Bar where &E: Into<Bar> {
  |               +++++++++

Ideally the output should suggest adding a HRTB like this:

pub fn works<E>(e: E) -> Bar where for<'e> &'e E: Into<Bar> {
    (&e).into()
}

TBH, HRTB are a very obscure feature to me, and it is not obvious in which circumstances I need to use them. This is one of those, and the compiler should suggest this to me.

I think there are quite some usecases when you have a Into / From that works with a reference, and you want to write code that is generic over that Into / From type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-papercutDiagnostics: An error or lint that needs small tweaks.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions