项目作者: mcuadros

项目描述 :
Go structures with default values using tags
高级语言: Go
项目地址: git://github.com/mcuadros/go-defaults.git
创建时间: 2014-01-14T00:27:02Z
项目社区:https://github.com/mcuadros/go-defaults

开源协议:MIT License

下载


go-defaults Build Status GoDoc GitHub release

Enabling stuctures with defaults values using struct tags.

Installation

The recommended way to install go-defaults

  1. go get github.com/mcuadros/go-defaults

Examples

A basic example:

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

Caveats

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