Skip to content

Returning an impl Trait in associated type position results in error at point-of-use instead of point-of-definition #72614

Closed as not planned
@Nemo157

Description

@Nemo157

Example (playground):

pub trait Foo {
    type Bar: std::ops::Add<Self::Bar>;
    fn bar(self) -> Self::Bar;
}

impl<T: std::ops::Add<T>> Foo for T {
    type Bar = T;
    fn bar(self) -> Self::Bar {
        self
    }
}

pub fn foo() -> impl Foo<Bar = impl std::ops::Sub<usize>> {
    5usize
}

fn main() {
    foo().bar() - 4usize;
}

This should error at the definition of foo since impl std::ops::Sub<usize> does not satisfy the std::ops::Add bound required by Foo::Bar. Instead it errors at the use-site in main, and if that line is deleted (e.g. if this is a pub fn in a library) there is no error.

error[E0277]: cannot add `impl std::ops::Sub<usize>` to `impl std::ops::Sub<usize>`
  --> src/main.rs:18:11
   |
18 |     foo().bar() - 4usize;
   |           ^^^ no implementation for `impl std::ops::Sub<usize> + impl std::ops::Sub<usize>`
   |
   = help: the trait `std::ops::Add` is not implemented for `impl std::ops::Sub<usize>`

Metadata

Metadata

Assignees

Labels

A-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.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