-
Notifications
You must be signed in to change notification settings - Fork 1.8k
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>,
}