Partial Structs
Partial structs are structs that can be partially initialized. Partial structs are useful when you want to initialize a struct with only a few fields, and set of default values for the rest.
Partial structs have great limitations compared to regular structs, when dealing with them.
- The compiler doesn't assume the presence of any field in a partial struct, therefore a nullish coaslescing operator ?? is required to access their fields.
- Partial Structs are read only, and cannot be modified. You will have to transform them into concrete structures to modify them. (see merge operator below)
Since this is troublesome and verbose, it is possible to merge partial structs with regular structs. Merging is done through >> or << operator depending on which direction you want to merge.
Merge Operator
- >>: The >> operator would merge all fields from left struct to the one on the right
- <<: The << operator would merge all fields from right struct to the one on the left.
Merge operator also works with regular structs on both sides, and would only merge the common fields between the two structs, and would not add any new fields.
Why spread operator doesn't work
The spread operator ... is not used for merging partial structs with concrete structs, for a simple reason: The spread operator changes the the type of the struct, i.e it adds fields to the struct:
The partial struct is not guarenteed to have all fields, hence the spread operator would not work as expected. Hence to merge.
Type Checking for partial structs
Type checking for partial structs is different compared to regular structs.
For example:
For partial structs, as long as the other type has some fields that are present in the partial struct, the type checking would pass.
Partial Struct Member Access
Because the values of the partial struct are not aguarenteed to be present (at least from the compiler's perspective), reading a field is required to be wrapped with a nullish coalescing operator ??. As of writing, it is not possible. Partial structs are read only. The reason the following.
At runtime, all objects must have rigid structures, the only thing that can be extended is the size are arrays.
The issue here is that p is a partial struct, and references a struct that has only two fields allocated at runtime. Hence, accessing p.z would be an out of bounds access.
In summary:
Nullable Partial Struct
Partial is not empty. A partial struct, when initialized, must have at least one field set, otherwise, use nullable instead.
In this example, if coords is null or the field coords.x is not set, x1 will be set to 1.0f in both cases.
Additional Notes
partial applies only the top level struct, nested fields are not inherently partial anlesunless otherwise specified.
Compiler Error: Type mismatch, expected struct{x:u32,y:u32} but found struct{x:u32}: Type mismatch, expected struct with at least 2 fields, got 1