Skip to main content

Optional type

Description

Instead of using pointers, ogen generates generic wrappers.

For example, OptNilString is string that is optional (no value) and can be null.

// OptNilString is optional nullable string.
type OptNilString struct {
Value string
Set bool
Null bool
}

Multiple convenience helper methods and functions are generated, some of them:

// IsSet returns true if OptNilString was set.
func (o OptNilString) IsSet() bool
// Reset unsets value.
func (o *OptNilString) Reset()
// SetTo sets value to v.
func (o *OptNilString) SetTo(v string)
// IsSet returns true if value is Null.
func (o OptNilString) IsNull() bool
// Get returns value and boolean that denotes whether value was set.
func (o OptNilString) Get() (v string, ok bool)
// Or returns value if set, or given parameter if does not.
func (o OptNilString) Or(d string) string

func NewOptNilString(v string) OptNilString

Semantic

To implement decoder, ogen follows the rules below

Type

SchemaType
requiredT
optionalOpt[#T]
nullable, but requiredNil[#T]
optional & nullableOptNil[#T]

Decoder behavior

Schemano valuenullvalue
requiredErrorErrorOK
optionalSet=falseErrorSet=true
nullable, but requiredErrorNull=trueOK
optional & nullableSet=falseSet=true,Null=trueSet=true,Null=false

Semantic for arrays

For arrays semantic is slightly different

Type

SchemaType
required[]T
optional[]T
nullable, but required[]T
optional & nullableOptNil[#T]Array

Decoder behavior

Schemano valuenull[]non-empty array
requiredErrorErrorEmpty non-nil sliceNon-empty slice
optionalnil sliceErrorEmpty non-nil sliceNon-empty slice
nullable, but requiredErrornil sliceEmpty non-nil sliceNon-empty slice
optional & nullableSet=falseSet=true,Null=true, empty sliceSet=true,Null=false, empty sliceSet=true,Null=false, non-empty slice