Nilable types

Reference | Web Services


A drawback of Go’s system of zero values is that it introduces ambiguity: is the value of a field on your target object false because the web service client set the value to false, or because the value wasn’t supplied at all and Go defaulted the value to false?

Granitic gets around this problem by providing a set of ‘nilable’ types for bool, string, int64 and float64.

These types all implement the interface types.Nilable which provides a method IsSet() bool which can tell you if the value was provided by the client (true) or not (false).

Granitic has deep support for these types and the framework can use them interchangeably in the whole web request processing cycle, including body parsing, path binding, query binding and JSON/XML marshalling. Other parts of Granitic including rule based validation and query management also support these types.

Using nilable types in your target object

Given a target object:

type MyTarget struct {
  IntField    int
  BoolField   bool
  StringField string
  FloatField  float
}

Rewrite this as:

type MyTarget struct {
  IntField    *types.NilableInt64
  BoolField   *types.NilableBool
  StringField *types.NilableString
  FloatField  *types.NilableFloat64
}

Note that the fields must be declared as pointers to the nilable types.

Using values

Each of the nilable types provides a method to recover the value it contains. The method is named according to the type it returns - e.g. types.NilableBool.Bool()


Next: Validating data

Prev: Capturing data