add #[serde(default)] to Node (and, perhaps other similar structs) #18883
+2
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Objective
Many structs that implement
Serialize
andDeserialize
(when Bevy'sserialize
feature is enabled) also implementDefault
, but do not apply the#[serde(default)]
attribute. This requires those who want to deserialize said structs to explicitly specify all struct fields in their data-interchange format, even if they all end up being their default values.For example, I am trying to implement a plugin that allows me to specify a UI tree in JSON files. I noticed that when I tried to deserialize the
Node
component (which has 39 fields!) withserde
, I was met with an error that in essence would have required me to specify all fields ofNode
in the JSON file, of which I was only using non-default values for:height
width
border
flex_direction
Solution
Node
structSerialize
,Deserialize
, andDefault
?After applying this attribute on a local fork of Bevy, I was able to deserialize my UI tree exactly as intended with minimal markup in my JSON files.
There might be a reason not to do this that I am not aware of, I tried looking for similar past issues but could not find much conversation about
#[serde(default)]
. Documentation on this attribute can be found here.Testing
I did not write any formal tests for this. Informally, I simply added
#[serde(default)]
toNode
to a local fork of Bevy and successfully deserialized an instance ofNode
with default values not specified in my JSON file.Sample JSON
Note how I only needed to specify 4/39 fields for
Node
. Upon deserialization,serde
invokedNode::default()
to populate the missing fields.