Description
Given the following code:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=242a6ff23679df5d4ac2f718e0ce8415
fn make_iter<T>(vec: &Vec<T>) -> Iterator<Item = &T> {
vec.iter()
}
The current output is:
error[[E0782]](https://doc.rust-lang.org/stable/error-index.html#E0782): trait objects must include the `dyn` keyword
--> src/lib.rs:1:34
|
1 | fn make_iter<T>(vec: &Vec<T>) -> Iterator<Item = &T> {
| ^^^^^^^^^^^^^^^^^^^
|
help: add `dyn` keyword before this trait
|
1 - fn make_iter<T>(vec: &Vec<T>) -> Iterator<Item = &T> {
1 + fn make_iter<T>(vec: &Vec<T>) -> dyn Iterator<Item = &T> {
|
For more information about this error, try `rustc --explain E0782`.
Ideally the output should look like:
error[[E0???]](https://doc.rust-lang.org/stable/error-index.html#E0???): bare trait invalid in this position
--> src/lib.rs:1:34
|
1 | fn make_iter<T>(vec: &Vec<T>) -> Iterator<Item = &T> {
| ^^^^^^^^^^^^^^^^^^^
|
help: try adding `impl` keyword before this trait
|
1 - fn make_iter<T>(vec: &Vec<T>) -> Iterator<Item = &T> {
1 + fn make_iter<T>(vec: &Vec<T>) -> impl Iterator<Item = &T> {
|
For more information about this error, try `rustc --explain E0???`.
During my journey learning Rust, I've made this mistake a number of types, and pretty much 90% of the time the compiler error was misleading because my actual intention was an impl Trait
in that position. Suggesting dyn Trait
in this situation leads to confusion and, if an unwitting programmer accepts it, another error immediately following it.
I think rustc
should suggest impl Trait
before dyn Trait
in the argument and return type positions. Suggesting dyn Trait
in type argument positions such as Box<Trait>
and in non-function contexts would still make sense.