Skip to main content

Sum type

Sum type (also known as tagged union) is a type that can be one of multiple possible variants. ogen uses sum types to represent oneOf and some anyOf schemas.

oneOf schema
Sum:
oneOf:
- $ref: '#/components/schemas/Cat'
- $ref: '#/components/schemas/Dog'
Generated sum type
// Sum represents sum type.
type Sum struct {
Type SumType // switch on this field
Cat Cat
Dog Dog
}

// SumType is oneOf type of Sum.
type SumType string

// Possible values for SumType.
const (
CatSum SumType = "Cat"
DogSum SumType = "Dog"
)

Discriminator inference

To distinguish different cases, decoder need some pattern called discriminator.

Explicit discriminator

Generator may distinguish variants by special type field.

oneOf schema with explicit discriminator mapping
Sum:
oneOf:
- $ref: '#/components/schemas/Cat'
- $ref: '#/components/schemas/Dog'
discriminator:
propertyName: petType
mapping:
cat: '#/components/schemas/Cat'
dog: '#/components/schemas/Dog'

Type discriminator

Type discriminator is discriminator based on JSON type.

oneOf schema with type discriminator
ID:
oneOf:
- type: string
- type: integer

Unique fields discriminator

Unique fields discriminator is discriminator based on unique schema fields. In that case, Decoder select variant by field that available only in one of all variants.

For example, given that schema:

oneOf schema with unique fields discriminator
Sum:
oneOf:
- type: object
required:
- common-1
- unique-1
properties:
common-1:
type: string
unique-1:
type: string
- type: object
required:
- common-1
- unique-2
properties:
common-1:
type: string
unique-2:
type: string

a payload like this:

{"common-1": "foo", "unique-1": "bar"}

will indicate that the first variant be used.