README.md
1defaults
2========
3
4[![Build Status](https://travis-ci.org/creasty/defaults.svg?branch=master)](https://travis-ci.org/creasty/defaults)
5[![codecov](https://codecov.io/gh/creasty/defaults/branch/master/graph/badge.svg)](https://codecov.io/gh/creasty/defaults)
6[![GitHub release](https://img.shields.io/github/release/creasty/defaults.svg)](https://github.com/creasty/defaults/releases)
7[![License](https://img.shields.io/github/license/creasty/defaults.svg)](./LICENSE)
8
9Initialize structs with default values
10
11- Supports almost all kind of types
12 - Scalar types
13 - `int/8/16/32/64`, `uint/8/16/32/64`, `float32/64`
14 - `uintptr`, `bool`, `string`
15 - Complex types
16 - `map`, `slice`, `struct`
17 - Aliased types
18 - `time.Duration`
19 - e.g., `type Enum string`
20 - Pointer types
21 - e.g., `*SampleStruct`, `*int`
22- Recursively initializes fields in a struct
23- Dynamically sets default values by [`defaults.Setter`](./setter.go) interface
24- Preserves non-initial values from being reset with a default value
25
26
27Usage
28-----
29
30```go
31type Gender string
32
33type Sample struct {
34 Name string `default:"John Smith"`
35 Age int `default:"27"`
36 Gender Gender `default:"m"`
37
38 Slice []string `default:"[]"`
39 SliceByJSON []int `default:"[1, 2, 3]"` // Supports JSON
40 Map map[string]int `default:"{}"`
41 MapByJSON map[string]int `default:"{\"foo\": 123}"`
42
43 Struct OtherStruct `default:"{}"`
44 StructPtr *OtherStruct `default:"{\"Foo\": 123}"`
45
46 NoTag OtherStruct // Recurses into a nested struct by default
47 OptOut OtherStruct `default:"-"` // Opt-out
48}
49
50type OtherStruct struct {
51 Hello string `default:"world"` // Tags in a nested struct also work
52 Foo int `default:"-"`
53 Random int `default:"-"`
54}
55
56// SetDefaults implements defaults.Setter interface
57func (s *OtherStruct) SetDefaults() {
58 if defaults.CanUpdate(s.Random) { // Check if it's a zero value (recommended)
59 s.Random = rand.Int() // Set a dynamic value
60 }
61}
62```
63
64```go
65obj := &Sample{}
66if err := defaults.Set(obj); err != nil {
67 panic(err)
68}
69```
70