Check if boolean value is set in Go
Asked Answered
S

5

9

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?

Subconscious answered 11/4, 2017 at 16:14 Comment(2)
Just out of curiosity: Which part of the language spec or the Tour of Go makes you think that there are things in Go which are "unset"?Variscite
@Volker: Just out of curiosity: What's the point of being that rude? Don't imply that people can only ask questions here if they have read the complete language spec. This is not how SOF works.Often
A
24

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

Arrogant answered 11/4, 2017 at 16:23 Comment(1)
Thanks, I was afraid there was no difference, but hopefully I can work the pointer solution in without to much pain.Subconscious
P
3

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?

Pontifex answered 11/4, 2017 at 16:22 Comment(0)
M
2

You may think of using 3-state booleans: https://github.com/grignaak/tribool

Machinery answered 11/4, 2017 at 17:59 Comment(0)
F
0

Yes. You have to use *bool instead of primitive bool

Fragrant answered 5/8, 2020 at 5:24 Comment(0)
D
0

No, you cannot. Alternatively you can use iota

package main

import "fmt"

type Status int

const (
    Unset Status = iota
    Active
    InActive
)

func (s Status) String() string {
    switch s {
    case Active:
        return "active"
    case InActive:
        return "inactive"
    default:
        return "unset"
    }
}

func main() {
    var s Status
    fmt.Println(s) // unset

    s = Active
    fmt.Println(s) // active
}
Detrimental answered 19/8 at 20:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.