Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if boolean value is set in Go

Tags:

boolean

go

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?

like image 760
hobberwickey Avatar asked Apr 11 '17 16:04

hobberwickey


2 Answers

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

like image 132
captncraig Avatar answered Sep 22 '22 02:09

captncraig


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?

like image 39
keno Avatar answered Sep 25 '22 02:09

keno