Skip to content

Recommending .to_owned() instead of .to_string() #5600

Closed
@ClementNerma

Description

@ClementNerma

I currently have a place in my code when I accidently converted an &str to a String using the format! macro, which is not the best thing to do. So when I run Clippy it reported this:

warning: useless use of `format!`
   --> mrvm_tools/src/exceptions/native.rs:137:42
    |
137 |             Self::DivisionOrModByZero => format!("<long message>"),
    |                                          ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `"<long message>".to_string()`

The problem here is the recommandation of .to_string(). As you can find in many explanations on vairous forums, .to_owned() is preferred to .to_string() as the latter may result in additional allocations to perform the conversion, while .to_owned() directly converts the value to a String.

So I think the lint should display this instead:

warning: useless use of `format!`
   --> mrvm_tools/src/exceptions/native.rs:137:42
    |
137 |             Self::DivisionOrModByZero => format!("<long message>"),
    |                                          ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_owned()`: `"<long message>".to_owned()`

If I miss a reason that makes Clippy recommend .to_string() over .to_owned() please let me know, I might be mistaken here but I think it would be better to recommend .to_owned().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions