Using bare trait where not possible should suggest to use a trait object or generic bound #35825
Labels
A-diagnostics
Area: Messages for errors, warnings, and lints
A-suggestion-diagnostics
Area: Suggestions generated by the compiler applied by `cargo fix`
A-trait-system
Area: Trait system
C-enhancement
Category: An issue proposing an enhancement or a PR with one.
D-newcomer-roadblock
Diagnostics: Confusing error or lint; hard to understand for new users.
T-compiler
Relevant to the compiler team, which will review and decide on the PR/issue.
The following code snippet will generate an E0277 error - I've elided some as it's not entirely necessary for the whole context, but this is not runnable:
E0277 indicates the following message:
I want to stress that yes, this error is factually correct: The reason why I have this error is because the naked trait
Iterator
has no defined size at compile time, and that the solution is to eitherBox
or borrow anIterator
(and thus rely on dynamic dispatch) or convertdo_something
into a generic function so that it is then monomorphised and Rust is aware of the size of the object at compile time.My suggestion is that the error message is not entirely clear: While it is true that the error is due to the trait size being undefined, coming from another language (like C#/Java/TypeScript) which uses interfaces, this can be confusing as traits are almost-but-not-quite analogous to interfaces. It may be useful to add an extra note to this error message (or accompanying docs) when passing a bare trait with something along the lines of:
And explain in some basic detail the difference between these approaches. For example:
Note: This behaviour led me to write this article when trying to fully understand the topic.
The text was updated successfully, but these errors were encountered: