Representing optional struct fields?

1,829 views
Skip to first unread message

jasdel

unread,
Oct 21, 2015, 1:56:09 PM10/21/15
to golang-nuts

Sometimes we have structs with optionally set fields where the zero value of the field is meaningful, e.g empty string, false, and 0. Such as in API requests, responses, or configurations. I'm curious what your preferred way of representing these optional fields in the struct is? Do you use generated, or handwritten, helper code for setting the fields, or do you just set the values inline?


I've seen a few common ways of representing the optional fields pointers, option types, and custom maps. Each of these have their own plus, minuses, and situations where one might be better than another. Where would you use one versus another?


Pointers seem to be the simplest way of representing the optional fields with minimal extra code. They also natively work well with marshallers' "omitempty" directive. A downside of pointers though, is they open you up to nil dereference panics when reading their values without first checking for nil. This is more prevalent in something like an API response or configuration which contains these optional fields. In addition in order to get the address of a literal, function return, or map's element value you need to set the value to a local variable first, or use a helper function for that type so you can inline set the optional field. Using pointers may also cause an additional allocations for each field.


Option types are interesting because they wrap the type with an additional boolean set state. The set state takes over the set or unset state pointers provided. Option types remove the need for additional allocations, and the risk of nil dereferences when reading the value. They do have some significant drawbacks though. You probably will need custom marshaling for each option type wrapper. In addition their value must be set and read with getters and setters, which complicates the usage of the field in your code.


What is your preferred way of representing and using optional fields?


- jasdel


Egon

unread,
Oct 21, 2015, 2:18:09 PM10/21/15
to golang-nuts
It depends on what the actual context and problem is. :)

These all are good ways of implementing it, but the decision which one is best, depends on which forces are at play. You choose the solution that makes the best trade-offs for a given situation.

I think you pretty well covered different ways of implementing it and pros/cons.

As general guideline, do as little as possible:

use different requests -- when not many options
omitempty -- when there are few optional fields
struct + isempty flag / pointers -- a more complicated situation, i.e. when optional params happen together
option types -- when things are more complicated
something else -- when previous aren't sufficient for some reason

+ Egon
Reply all
Reply to author
Forward
0 new messages