Skip to content

Commit 29aae67

Browse files
committed
Adding notes on use of omitempty
Signed-off-by: Jiri Podivin <[email protected]>
1 parent 728bb2a commit 29aae67

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

developer.md

+26
Original file line numberDiff line numberDiff line change
@@ -184,3 +184,29 @@ for the `PasswordSelectors` field will be used. But when the
184184
`passwordSelectors` field is in the input but only defines the `database` field
185185
but not the `service` then the default defiened at `Service` field will be
186186
used.
187+
188+
## CRD fields with omitempty
189+
190+
Some fields omited from serialization using the `omitempty` marker,
191+
thus sparing time that would have to be used for encoding them.
192+
By marking field with omitempty, it will not be encoded, if it contains
193+
value defined as empty. This value is type dependent, for example `0` for integers,
194+
or nil for pointers.[0]
195+
196+
It is necessary for the operator code to expect this behavior,
197+
and special care must be taken when it comes to omitting pointers.
198+
All pointer fields marked as `omitempty` must be checked if they are not nil before use.
199+
200+
When used in conjuction with `Optional` kubebuilder validation, the field
201+
has to be assumed to be empty by default and treated as such.
202+
Pointers to booleans and integers can be especially tricky in cases like this.
203+
Checks for nil value must be implemented before the field is used.
204+
Since it may happen that their empty value, that is false or 0, is actually meaningful.
205+
Then the optional field may be set to value of nil pointer.
206+
207+
The `omitempty` should therefore only be used on cases when one deals with
208+
pointers in general, or pointers to structs specifically.
209+
All other types do not benefit from being omitted.
210+
211+
[0] https://pkg.go.dev/encoding/json#Marshal
212+
[1] https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#optional-vs-required

0 commit comments

Comments
 (0)