rust-lang / rust-lang/rust-clippy
New lint: deriving Deserialize on a struct with &str
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
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>,
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue names no files, tests, or entry points. Start by locating Clippy's existing derive-related lint and test patterns, then determine how to detect borrowed &str fields in Deserialize derives. Done means the lint recommends Cow<'de, str> with #[serde(borrow)] and covers the provided Bad and Good examples without false positives.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100