Skip to content

Trait with associated type bounds cannot be made into an object because it uses Self as a type parameter #80256

Open
@ldr709

Description

@ldr709

A simplified example where this shows up is the following trait.

trait Conversion {
    type Source: Into<Self::Target>;
    type Target;
}

(Full code)

If you try to make a trait object, say &dyn Conversion<Source = String, Target = Box<str>>, then Rust errors:

error[E0038]: the trait `Conversion` cannot be made into an object
  --> src/main.rs:14:12
   |
1  | trait Conversion {
   |       ---------- this trait cannot be made into an object...
2  |     type Source: Into<Self::Target>;
   |                  ------------------ ...because it uses `Self` as a type parameter in this
...
14 |     let b: &dyn Conversion<Source = String, Target = Box<str>> = &a;
   |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Conversion` cannot be made into an object

If the bound was something like Source: Into<Self> this error would make sense, but instead the bound references another associated type, which all must be fully specified when making a trait object type anyway.

This problem does not seem to occur when associated types are used to define functions in the trait, as creating a &dyn Deref<Target = ...> trait object works.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-dyn-compatibilityArea: Dyn compatibility (formerly: object safety)A-dyn-traitArea: trait objects, vtable layoutA-trait-systemArea: Trait systemC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types 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