-
Notifications
You must be signed in to change notification settings - Fork 668
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[cleanup] Minor cleanup in serde default (#10203)
Discovered simplified way to have default values in serde for structs only when ALL fields have a default. We can have a #[serde(default)] attribute for the whole struct and any missing fields are picked up from the Default::default() implementation of the struct. Playground example ``` #[derive(Serialize, Deserialize, Debug)] #[serde(default)] struct Point { x: i32, y: i32, } impl Default for Point { fn default() -> Self { Self { x: 1, y: 2 } } } #[test] fn serde() { let point = Point { x: 10, y: 20 }; let serialized = serde_json::to_string(&point).unwrap(); println!("serialized = {}", serialized); let deserialized: Point = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); // I get Point { x: 10, y: 20 } let serialized = "{\"x\":15}"; let deserialized: Point = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); // I get Point { x: 15, y: 2 } } ``` Bit more context here: #10202
- Loading branch information
Shreyan Gupta
authored
Nov 17, 2023
1 parent
2c7243d
commit 23aa2ca
Showing
3 changed files
with
10 additions
and
57 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters