mcuadros / go-defaults

Go structures with default values using tags

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Default value of true makes it impossible to set a field to false

Noah-Huppert opened this issue · comments

If you make a field's default value true you can never set it to false. The go-defaults library will always override the false value to be true.

I made a repository with a small self contained example: link.

I don't think there is a way to fix this. Maybe go-defaults could simply ignore any bool fields. Or maybe make a custom bool type for go-defaults which keeps track of if its value has been set.

from README.md:

#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:

example := ExampleBasic{
Bar: 0,
}
defaults.SetDefaults(example)
fmt.Println(example.Bar) //Prints: 33 instead of 0 (which is zero value for int)

example.Bar = 0 // set needed zero value AFTER applying defaults
fmt.Println(example.Bar) //Prints: 0

Oops I probably should've closed this a while ago. I went back and saw that caveat.