Is it possible to differentiate between false
and an unset boolean value in go?
For instance, if I had this code
type Test struct {
Set bool
Unset bool
}
test := Test{ Set: false }
Is there any difference between test.Set
and test.Unset
and if so how can I tell them apart?
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With