rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
10.89k stars 1.46k forks source link

lint: Unnecessary intermediary conversion #12698

Open sgued opened 3 weeks ago

sgued commented 3 weeks ago

What it does

This lints against using from twice using an itermediary type when there is an From implementation in one step

Advantage

Drawbacks

It might be possible that the 2 implementations do not have the same behaviour, but based on the documentation of From, this does not really fit the contract of the trait.

Example

With the context:

struct A;
struct B;
struct C;

impl From<B> for A {
    fn from(_: B) -> Self {
        Self
    }
}

impl From<C> for A {
    fn from(_: C) -> Self {
        Self
    }
}

impl From<C> for B {
    fn from(_: C) -> Self {
        Self
    }
}
let c: C = …;
let b: B = c.into();
let a: A = b.into();

Could be written as:

let c: C = …;
let a: A = c.into();
matthiaskrgr commented 3 weeks ago

This looks like it should be a compiler optimization tbh.

sgued commented 3 weeks ago

In the vast majority of cases the compiler is already able to optimize this. But optimization is not the main goal. The main goal is to make the code more concise and readable. One other aspect is to "teach" users that a dependency has added a From implementation for their use-case and they don't have to work around it anymore.