Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a lint to check for functions/methods that could be From #14018

Open
FalkWoldmann opened this issue Jan 17, 2025 · 2 comments
Open

Add a lint to check for functions/methods that could be From #14018

FalkWoldmann opened this issue Jan 17, 2025 · 2 comments
Labels
A-lint Area: New lints

Comments

@FalkWoldmann
Copy link

What it does

Checks for functions and methods that could be a From impl (we could even do this for TryFrom)

Advantage

  • Makes the code more idiomatic

Drawbacks

No response

Example

struct StructA {
    some_field: String
}

struct StructB {
    some_field: String
}

fn map_to_struct_b(a: StructA) -> StructB {
    StructB {
        some_field: a.some_field
    }
}

impl StructA {
    fn to_struct_b(self) -> StructB {
        StructB {
            some_field: self.some_field
        }
    }
}

Could be written as:

impl From<StructA> for StructB {
    fn from(a: StructA) -> Self {
        StructB {
            some_field: a.some_field
        }
    }
}
@FalkWoldmann FalkWoldmann added the A-lint Area: New lints label Jan 17, 2025
@samueltardieu
Copy link
Contributor

From is typically implemented for lossless, value-preserving obvious conversions. For example, String::from(&str) would give you a String which has the same content of the &str, and you can even build a &str back from the String.

This works in your example, because you simply copy the field. On the other hand, I think StructB should not implement From<StructA> in the following case:

struct StructA<'a> {
    some_field: &'a str
}

struct StructB {
    some_field: String
}

impl StructA<'_> {
    fn to_struct_b(self) -> StructB {
        StructB { some_field: self.some_field.to_uppercase() }
    }
}

Finding a criteria to determine if From should be proposed by default is not easy.

@FalkWoldmann
Copy link
Author

Perhaps we can start with linting these simple and obvious cases?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

2 participants