Closed
Description
I have encountered associated types for the first time through a build error.
Associated types are used infrequently and other programmers will probably encounter the feature for the first time in a similar manner.
The error was particularly confusing because I thought that I was asked to provide a generic type to a type that was not generic. I was left rather puzzled.
It would be particularly helpful if in this instance the compiler could use information passed in from the single call point (i.e., from main
) to suggest a fix (Feather<Error=String>
).
The error message:
error[E0191]: the value of the associated type `Error` (from the trait `Feather`) must be specified
--> src/main.rs:22:83
|
3 | type Error;
| ----------- `Error` defined here
...
22 | fn pick_feather<'a>(first: bool, f1: &'a dyn Feather, f2: &'a dyn Feather) -> &'a dyn Feather {
| ^^^^^^^^^^^ associated type `Error` must be specified
A short program to replicate the error message:
trait Feather {
type Error;
fn float(&self, x: i32, y: Self::Error) -> Result<i32, Self::Error> {
if x > 0 {
Ok(x)
}
else {
Err(y)
}
}
}
struct RedFeather {}
impl Feather for RedFeather {
type Error = String;
}
struct BlueFeather {}
impl Feather for BlueFeather {
type Error = String;
}
fn pick_feather<'a>(first: bool, f1: &'a dyn Feather, f2: &'a dyn Feather) -> &'a dyn Feather {
if first {
f1
}
else {
f2
}
}
fn main() {
let red = RedFeather {};
let blue = BlueFeather {};
let feather = pick_feather(false, &red, &red);
feather.float(3, "oh no".to_owned()).unwrap();
}
Ideally, the final suggestion would read:
fn pick_feather<'a>(
first: bool,
f1: &'a dyn Feather<Error=String>,
f2: &'a dyn Feather<Error=String>) -> &'a dyn Feather<Error=String> {
Metadata
Metadata
Assignees
Labels
Area: Associated items (types, constants & functions)Area: Messages for errors, warnings, and lintsArea: Suggestions generated by the compiler applied by `cargo fix`Category: An issue proposing an enhancement or a PR with one.Diagnostics: Confusing error or lint; hard to understand for new users.Relevant to the compiler team, which will review and decide on the PR/issue.