Skip to content

Boolean default=true issue #60

Description

@superstes

Greetings.

Thanks for this super useful library 👍

I've seen that there is an undocumented issue when setting a boolean to default="true"

If a user set's the value to false explicitly - it will still be reverted to true (as there is no nil value).

The fix is to use a *bool instead as this can be either true, false or unset.

Could make sense to add a short info to the Readme so users do not waste time on it. (:

Example that has the issue:

type config struct {
	Enabled       bool       `default:"true"`
}


func test() {
	cnf := config{Enabled: true}
	if err := defaults.Set(&cnf); err != nil {
		log.Fatalln("failed to set config defaults")
	}
	log.Printf("Value: %v\n", cnf)  // true

	cnf = config{Enabled: false}
	if err := defaults.Set(&cnf); err != nil {
		log.Fatalln("failed to set config defaults")
	}
	log.Printf("Value: %v\n", cnf)  // true
}

Example that works:

type config struct {
	Enabled *bool `default:"true"`
}

func test() {
	isEnabled := true
	cnf := config{Enabled: &isEnabled}
	if err := defaults.Set(&cnf); err != nil {
		log.Fatalln("failed to set config defaults")
	}
	log.Printf("Value: %v\n", cnf) // true

	isEnabled = false
	cnf = config{Enabled: &isEnabled}
	if err := defaults.Set(&cnf); err != nil {
		log.Fatalln("failed to set config defaults")
	}
	log.Printf("Value: %v\n", cnf) // false
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions