github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/defaults/README.md (about)

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