goboolean

Check if boolean value is set in 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?


Solution

  • 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