Rust errors / Types and traits
Rust compiler error · checked with rustc 1.99.0
Rust error E0222: ambiguous associated type `Color` in bounds of `BoxCar`
What it meansAn attempt was made to constrain an associated type.
What rustc prints
error[E0222]: ambiguous associated type `Color` in bounds of `BoxCar` --> main.rs:11:37 | 2 | type Color; | ---------- ambiguous `Color` from `Vehicle` ... 6 | type Color; | ---------- ambiguous `Color` from `Box` ... 11 | fn dent_object<COLOR>(c: dyn BoxCar<Color=COLOR>) {} // Invalid constraint | ^^^^^^^^^^^ ambiguous associated type `Color` | = help: consider introducing a new type parameter `T` and adding `where` constraints: where T: BoxCar, T: Vehicle::Color = COLOR, T: Box::Color = COLOR
Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
The compiler team's explanation
An attempt was made to constrain an associated type.
Erroneous code example:
pub trait Vehicle {
type Color;
}
pub trait Box {
type Color;
}
pub trait BoxCar : Box + Vehicle {}
fn dent_object<COLOR>(c: dyn BoxCar<Color=COLOR>) {} // Invalid constraint
In this example, BoxCar has two supertraits: Vehicle and Box. Both of these traits define an associated type Color. BoxCar inherits two types with that name from both supertraits. Because of this, we need to use the fully qualified path syntax to refer to the appropriate Color associated type, either <BoxCar as Vehicle>::Color or <BoxCar as Box>::Color, but this syntax is not allowed to be used in a function signature.
In order to encode this kind of constraint, a where clause and a new type parameter are needed:
pub trait Vehicle {
type Color;
}
pub trait Box {
type Color;
}
pub trait BoxCar : Box + Vehicle {}
// Introduce a new `CAR` type parameter
fn foo<CAR, COLOR>(
c: CAR,
) where
// Bind the type parameter `CAR` to the trait `BoxCar`
CAR: BoxCar,
// Further restrict `<BoxCar as Vehicle>::Color` to be the same as the
// type parameter `COLOR`
CAR: Vehicle<Color = COLOR>,
// We can also simultaneously restrict the other trait's associated type
CAR: Box<Color = COLOR>
{}From rustc --explain E0222 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0308mismatched types
- E0277the trait bound is not satisfied
- E0599no method named X found in the current scope
- E0433failed to resolve
- E0220associated type `Baz` not found for `Self`
- E0221ambiguous associated type `A` in bounds of `Self`
- E0223ambiguous associated type
- E0224at least one trait is required for an object type
Up next
Often hit nextE0308: mismatched typesA related error from the same family.Read it next →Did this answer your question?