Skip to content

Lint against using generic conversion traits when concrete methods are available #36443

Closed
@sfackler

Description

@sfackler

The standard library's backwards compatibility rules allow the addition of new trait implementations even though this can cause previously working code to hit type inference failures in some contexts. Generic conversion traits (From, AsRef, Borrow, etc) frequently come up in regression reports since they're commonly implemented multiple times for a given type.

Because of this, the standard library commonly provides concrete methods with identical functionality which can be used to avoid these kinds of issues. For example, the String::into_bytes method has an equivalent signature to the Into::<Vec<u8>>::into method on String.

For example, the code in #36352 passed the result of the Borrow::borrow method into the From::from method, which failed to type infer after a second From implementation was added to String. This could have been avoided if the concrete .as_bytes() method was used instead of .borrow().

We should consider adding a lint, probably backed by annotations on the impls, which warn against calling the generic conversion trait methods in concrete contexts when a concrete method is available.

cc @rust-lang/libs

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions