Misc 5 @WaffleLapkin @BoxyUwU
Warning: this quiz is still "work-in-progress", some questions might not have good explanations (or any at all), formatting/structure/titles/etc are not final, and so on. You might want to return here on a later date.
trait Super {
fn assoc() -> Self;
}
trait Sub: Super {}
fn f<T: Sub>() -> T {
Sub::assoc()
}
fn main() {}
Solution
error[E0782]: expected a type, found a trait
--> examples/misc_5.rs:8:5
|
8 | Sub::assoc()
| ^^^
|
help: you can add the `dyn` keyword if you want a trait object
|
8 | <dyn Sub>::assoc()
| ++++ +
For more information about this error, try `rustc --explain E0782`.
error: could not compile `code` (example "misc_5") due to 1 previous error
The diagnostic can be confusing, but the issue here is that you can't refer to items from super traits through sub traits. Even though Sub
has a super trait Super
, you can't use Sub::assoc()
.
The diagnostic assumes that you meant to use Sub
as a type, not a trait, which requires the dyn
keyword. (In this specific case this assumption doesn't make sense, since Sub
is not dyn compatible)
You can use Super::assoc()
though, i.e. this compiles just fine:
trait Super {
fn assoc() -> Self;
}
trait Sub: Super {}
fn f<T: Sub>() -> T {
Super::assoc()
}
Trait::assoc
is a shorter version of <_ as Trait>::assoc
(aka fully qualified path).