package tool import ( "math/rand" "testing" "github.com/creasty/defaults" "github.com/stretchr/testify/assert" ) 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}"` 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 } } func TestDefaults(t *testing.T) { obj := &Sample{} err := Default(obj) assert.Nil(t, err) assert.Equal(t, obj.Age, 27) assert.Equal(t, obj.Gender, Gender("m")) assert.Equal(t, obj.Slice, []string{}) assert.Equal(t, obj.Map, map[string]int{}) assert.Equal(t, obj.MapByJSON, map[string]int{"foo": 123}) }