项目作者: xunleii

项目描述 :
Go structures with default values using tags
高级语言: Go
项目地址: git://github.com/xunleii/go-defaults.git
创建时间: 2019-09-09T18:56:40Z
项目社区:https://github.com/xunleii/go-defaults

开源协议:MIT License

下载


go-defaults

Actions Status
GoDoc
GitHub release

(Mostly inspired by github.com/mcuadros/go-defaults)
Enabling stuctures with defaults values using struct tags.

Installation

The recommended way to install go-defaults

  1. go get gopkg.in/xunleii/go-defaults

Examples

A basic example (based on github.com/mcuadros/go-defaults) :

  1. import (
  2. "fmt"
  3. "github.com/xunleii/go-defaults"
  4. )
  5. type ExampleBasic struct {
  6. Foo bool `default:"true"` //<-- StructTag with a default key
  7. Bar string `default:"33"`
  8. Qux int8
  9. Dur time.Duration `default:"1m"`
  10. }
  11. func NewExampleBasic() *ExampleBasic {
  12. example := new(ExampleBasic)
  13. defaults.SetDefaults(example) //<-- This set the defaults values
  14. return example
  15. }
  16. ...
  17. test := NewExampleBasic()
  18. fmt.Println(test.Foo) //Prints: true
  19. fmt.Println(test.Bar) //Prints: 33
  20. fmt.Println(test.Qux) //Prints:
  21. fmt.Println(test.Dur) //Prints: 1m0s

Caveats (also based on github.com/mcuadros/go-defaults)

At the moment, the way the default filler checks whether it should fill a struct field or not is by comparing the current field value with the corresponding zero value of that type. This has a subtle implication: the zero value set explicitly by you will get overriden by default value during SetDefaults() call. So if you need to set the field to container zero value, you need to set it explicitly AFTER setting the defaults.

Take the basic example in the above section and change it slightly:

  1. example := ExampleBasic{
  2. Bar: 0,
  3. }
  4. defaults.SetDefaults(example)
  5. fmt.Println(example.Bar) //Prints: 33 instead of 0 (which is zero value for int)
  6. example.Bar = 0 // set needed zero value AFTER applying defaults
  7. fmt.Println(example.Bar) //Prints: 0

License

MIT, see LICENSE