Skip to content

Binding associated type requires redundancy. #40093

Closed
@frankmcsherry

Description

@frankmcsherry

I've been told this may be intended behavior, in which case treat this as a vote for "I think it shouldn't be". :)

If you have a trait with a constraint on an associated type,

pub trait Test {
    type Item;
    type Bundle: From<Self::Item>;
}

You can use the trait without constraints, like so

fn works<T>()
    where T: Test,
{ }

but if you instantiate any associated types it breaks.

fn fails<T>() 
    where T: Test<Item = String>
{ } 
// error[E0277]: the trait bound `<T as Test>::Bundle: std::convert::From<std::string::String>` is not satisfied
// ..
//   = help: consider adding a `where <T as Test>::Bundle: std::convert::From<std::string::String>` bound

You can solve the problem by copy/paste with the trait constraint.

fn works<T>()
    where T: Test<Item = String>,
          T::Bundle: From<T::Item>,
{ }

I've been pointed at 28055, related to super traits (same, maybe not?). I think the invoked argument is that "too many inferred constraints leads to spooky action at a distance", which I understand.

At the moment, I very much feel like the maintainability trade-off is in totally the wrong direction, though. If this associated type changes, or goes away, or has a new constraint, all existing code that may not care about the type breaks until you copy/paste in the (I feel) redundant requirements the trait already imposes.

Edit: see also #34106.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)C-bugCategory: This is a bug.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