Skip to main content

Apply defaults

Put stable, local defaults on fields, then apply them before validation:

type Database struct {
Driver string `default:"sqlite"`
MaxOpenConns int `default:"1"`
Timeout time.Duration `default:"5s"`
}

type CLIConfig struct {
Database *Database `default:"dive"`
Labels map[string]string `default:"alloc"`
}

binding, err := model.NewBinding[CLIConfig]()
if err != nil {
return err
}
cfg := CLIConfig{}
if err := binding.ApplyDefaults(&cfg); err != nil {
return err
}
// cfg.Database is allocated; Driver is "sqlite"; Labels is an empty map.

Literal defaults fill zero scalar values and leave nonzero values in place. A nil pointer to a scalar is allocated for a literal. default:"dive" allocates a nil pointer to a struct and traverses it; existing nested structs are traversed automatically. default:"alloc" creates an empty slice or map when nil. An invalid or out-of-range numeric literal returns an error.

For existing slice or array elements that are structs, use defaultElem:"dive":

type Endpoint struct {
Timeout time.Duration `default:"2s"`
}
type Runner struct {
Endpoints []Endpoint `defaultElem:"dive"`
}

Map values that are structs are traversed when defaults are applied, even without defaultElem:"dive". Literal defaultElem values are currently ignored; set element literals in application code if needed.

Call ApplyDefaults again after adding new elements or clearing fields. It evaluates zero values on every call. To apply defaults and then the binding's environment snapshot before validation, use ValidateWithDefaults(ctx, &cfg).