Help us shape the future of Go! Take the 2026 Go Developer Survey

defaults

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 4 Imported by: 0

README

Default values

typedcfg applies defaults before decoding sources; decoded explicit zero values are preserved. The standalone helper defaults.SetDefaults(&cfg) fills zero fields on an existing struct.

type Config struct {
    Port int `json:"port" default:"8080"`
    Timeout time.Duration `json:"timeout" default:"30s"`
    Tags []string `json:"tags" default:"web,api"`
    Database struct {
        Host string `json:"host" default:"localhost"`
    } `json:"database"`
}

Supported tags: strings, signed/unsigned integers, floats, booleans, time.Duration, comma-separated string slices, and pointers to these types. Nested value structs are traversed automatically. Unsupported field kinds do not receive a default. This helper parses tags but does not validate application constraints or detect narrowing overflow when assigning numeric values to smaller field types.

A nil pointer needs its own default tag to be allocated; for a struct pointer use default:"" so nested defaults are visited. Non-nil pointers are preserved by this helper. Defaults are not recursively applied to collection elements or objects allocated later by the decoder. For straightforward predictable defaults, prefer nested value structs.

cfg := Config{}
if err := defaults.SetDefaults(&cfg); err != nil {
    return err
}

Documentation

Overview

Package defaults applies default tags to zero-valued struct fields.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetDefaults

func SetDefaults(ptr any) error

SetDefaults fills zero-valued fields from their default tags and recurses into nested value structs. Nil pointers require their own default tag to be allocated; existing non-nil pointers and collection elements are not traversed.

Supported tag format: `default:"value"`

Examples:

type Config struct {
    Port     int           `default:"8080"`
    Host     string        `default:"localhost"`
    Timeout  time.Duration `default:"30s"`
    Debug    bool          `default:"false"`
    Tags     []string      `default:"tag1,tag2,tag3"`
}

Inputs other than a pointer to a struct are ignored. Tag parsing errors are returned; application constraints and narrowing numeric overflow are not checked.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL