defaults

package module
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2023 License: MIT Imports: 6 Imported by: 567

README

defaults

CircleCI codecov GitHub release License

Initialize structs with default values

  • Supports almost all kind of types
    • Scalar types
      • int/8/16/32/64, uint/8/16/32/64, float32/64
      • uintptr, bool, string
    • Complex types
      • map, slice, struct
    • Nested types
      • map[K1]map[K2]Struct, []map[K1]Struct[]
    • Aliased types
      • time.Duration
      • e.g., type Enum string
    • Pointer types
      • e.g., *SampleStruct, *int
  • Recursively initializes fields in a struct
  • Dynamically sets default values by defaults.Setter interface
  • Preserves non-initial values from being reset with a default value

Usage

type Gender string

type Sample struct {
	Name   string `default:"John Smith"`
	Age    int    `default:"27"`
	Gender Gender `default:"m"`

	Slice       []string       `default:"[]"`
	SliceByJSON []int          `default:"[1, 2, 3]"` // Supports JSON

	Map                 map[string]int `default:"{}"`
	MapByJSON           map[string]int `default:"{\"foo\": 123}"`
	MapOfStruct         map[string]OtherStruct
	MapOfPtrStruct      map[string]*OtherStruct
	MapOfStructWithTag  map[string]OtherStruct `default:"{\"Key1\": {\"Foo\":123}}"`
    
	Struct    OtherStruct  `default:"{}"`
	StructPtr *OtherStruct `default:"{\"Foo\": 123}"`

	NoTag  OtherStruct               // Recurses into a nested struct by default
	OptOut OtherStruct `default:"-"` // Opt-out
}

type OtherStruct struct {
	Hello  string `default:"world"` // Tags in a nested struct also work
	Foo    int    `default:"-"`
	Random int    `default:"-"`
}

// SetDefaults implements defaults.Setter interface
func (s *OtherStruct) SetDefaults() {
	if defaults.CanUpdate(s.Random) { // Check if it's a zero value (recommended)
		s.Random = rand.Int() // Set a dynamic value
	}
}
obj := &Sample{}
if err := defaults.Set(obj); err != nil {
	panic(err)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CanUpdate

func CanUpdate(v interface{}) bool

CanUpdate returns true when the given value is an initial value of its type

func MustSet added in v1.5.1

func MustSet(ptr interface{})

MustSet function is a wrapper of Set function It will call Set and panic if err not equals nil.

func Set

func Set(ptr interface{}) error

Set initializes members in a struct referenced by a pointer. Maps and slices are initialized by `make` and other primitive types are set with default values. `ptr` should be a struct pointer

Types

type Setter

type Setter interface {
	SetDefaults()
}

Setter is an interface for setting default values

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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