defaults

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package defaults provides support for setting default values in struct fields based on the value of the "default" struct tag.

Example
package main

import (
	"fmt"
	"net/netip"

	"github.com/mattdowdell/sandbox/internal/drivers/config/defaults"
)

type MyStruct struct {
	Int    int    `default:"10"`
	Bool   bool   `default:"true"`
	String string `default:"hello"`
	Child  ChildStruct
}

type ChildStruct struct {
	Float float64    `default:"1.2"`
	Uint  uint       `default:"5"`
	Addr  netip.Addr `default:"127.0.0.1"`
}

func main() {
	s := &MyStruct{}

	if err := defaults.Set(s); err != nil {
		panic(err)
	}

	fmt.Println(s)
}
Output:
&{10 true hello {1.2 5 127.0.0.1}}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Set

func Set(target any) error

Set sets the fields of a struct to the values in the "default" struct tag. The target argument must be a pointer to a struct.

By default, the following types are natively supported:

- int, int, int16, int32, int64 via strconv.ParseInt. - uint, uint8, uint16, uint32, uint64, uintptr via strconv.ParseUint. - float32, float64 via strconv.ParseFloat. - bool via strconv.ParseBool. - string - time.Duration via time.ParseDuration.

Integer default values can be specified in binary, octal, decimal, and hexadecimal by adding the appropriate prefix. Unparseable values result in an error being returned.

Structs within structs are also supported under the assumption they contain their own set of supported types.

Support for types other than those explicitly supported can implement encoding.TextUnmarshaler. This can also be implemented for type aliases of the supported types to override the default behaviour. Types that are not supported natively and do not implement encoding.TextUmarshaler result in an error being returned.

Defaults are not applied in the following circumstances:

- Private fields are skipped. - Fields with a non-zero value are skipped. - Empty values of the "default" struct tag are skipped.

Types

This section is empty.

Jump to

Keyboard shortcuts

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