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.
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?
hobberwickey
I'm a self taught web developer, focused primarily on Javascript development (and of course the HTML/CSS that goes with it, but with a solid background in server-side scripting (PHP, Python, Ruby) which I use grab/save data from/to databases and do most of the logic on the client's computer. I'm currently freelancing and always looking for more work and working on a JS/Canvas based animation system called Animajig. I'll put a link up to it when it's live (hopefully around March/April 2013).
Updated on June 24, 2022Comments
-
hobberwickey almost 2 years
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
andtest.Unset
and if so how can I tell them apart?