Skip to content

New lint: deriving Deserialize on a struct with &str #5799

@couchand

Description

@couchand

What it does

Warn users that deriving Deserialize on something containing an &str is not a good generally idea. The lint would suggest deserializing into a Cow<'de, str> instead.

Many data formats escape strings in various ways, meaning the text cannot be deserialized without a copy. This will fail mysteriously at runtime, and only when the text field contains an escape sequence. It used to be a hard error in Serde, I'm not sure what happened since then.

Categories

  • Kind: clippy::correctness, as it "causes hard errors by default"

What is the advantage of the recommended code over the original code?

Failing mysteriously at runtime based on user input is not good. Deserializing into a Cow won't fail mysteriously at runtime.

Drawbacks

If you're absolutely sure that your payload contains no escape characters, you could use &str and might get annoyed by this lint. (On the other hand, one day maybe someone will stick a double-quote in a text field without warning you.)

Example

#[derive(Deserialize)]
struct Bad<'a> {
    name: &'a str,
}

Could be written as:

#[derive(Deserialize)]
struct Good<'a> {
    #[serde(borrow)]
    name: Cow<'a, str>,
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.L-suggestionLint: Improving, adding or fixing lint suggestionsT-macrosType: Issues with macros and macro expansion

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions