Skip to content

Permit impl methods whose bounds cannot be satisfied to have no body #20021

Open
@nikomatsakis

Description

@nikomatsakis

There is a curious case with where clauses where sometimes we can show that a method in an impl could not possibly be called. This is because the impl has more precise information than the trait. Here is an example:

    trait MyTrait<T> {
        fn method(&self, t: &T) where T : Eq;
    }

    struct Foo;
    struct Bar; // note that `Bar` does not derive `Eq`

    impl MyTrait<Bar> for Foo {
        fn method(&self, t: &T) where Bar : Eq { // <-- `Bar : Eq` cannot be satisfied!
        }
    }

We should permit the method body to be omitted in such a case. As a workaround, once #20020 is fixed, I imagine it would be possible to write an impl like this:

impl MyTrait<Bar> for Foo {
    fn method(&self, t: &T) { // no where clause at all
        panic!("Bar : Eq could not be satisfied");
    }
}

However, it is unfortunate to require that of the user. For one thing, perhaps it happens later that an impl of Eq is added for Bar -- now we have this method hanging around that will panic. It'd be nice to detect that statically.

The plan then would be to permit:

impl MyTrait<Bar> for Foo {
    fn method(&self, t: &T); // <-- no body or where clauses needed
}

This serves as a declaration that you believe this method could never be called. At trans time, we will generate a body that simply does the equivalent of panic!("unsatisfiable methodmethodinvoked").

I plan to open an amendment to the where clause RFC describing this particular case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-trait-systemArea: Trait systemC-feature-requestCategory: A feature request, i.e: not implemented / a PR.E-mediumCall for participation: Medium difficulty. Experience needed to fix: Intermediate.T-langRelevant to the language 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