Check if boolean value is set in Go

Solution 1

No, a bool has two possibilities: true or false. The default value of an uninitialized bool is false. If you want a third state, you can use *bool instead, and the default value will be nil.

type Test struct {
    Set *bool
    Unset *bool
}

f := false
test := Test{ Set: &f }

fmt.Println(*test.Set)  // false
fmt.Println(test.Unset) // nil

The cost for this is that it is a bit uglier to set values to literals, and you have to be a bit more careful to dereference (and check nil) when you are using the values.

Playground link

Solution 2

bool has a zero value of false so there would be no difference between them.

Refer to the zero value section of the spec.

What problem are you trying to solve that would require that kind of check?

Share:
Admin
Author by

Admin

Updated on June 24, 2022

Comments

  • Admin
    Admin about 1 month

Related