检查布尔值是否在Go中设置

huangapple go评论75阅读模式
英文:

Check if boolean value is set in Go

问题

在Go语言中,可以区分false和未设置的布尔值吗?

例如,如果我有以下代码:

type Test struct {
    Set bool
    Unset bool
}

test := Test{ Set: false }

test.Settest.Unset之间有什么区别,如果有的话,我该如何区分它们?

英文:

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?

答案1

得分: 20

不,bool类型有两种可能的取值:truefalse。未初始化的bool类型的默认值是false。如果你想要第三种状态,可以使用*bool类型,其默认值将为nil

type Test struct {
    Set *bool
    Unset *bool
}

f := false
test := Test{ Set: &f }

fmt.Println(*test.Set)  // false
fmt.Println(test.Unset) // nil

这样做的代价是,使用字面值设置值会有些丑陋,并且在使用这些值时需要更加小心地解引用(并检查是否为nil)。

Playground链接

英文:

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

答案2

得分: 3

bool 的零值是 false,所以它们之间没有区别。

请参考规范中的零值部分。

你试图解决什么问题,需要进行这种检查?

英文:

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?

答案3

得分: 2

你可以考虑使用三态布尔值:https://github.com/grignaak/tribool

英文:

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

答案4

得分: 0

是的。你必须使用*bool而不是原始的bool

英文:

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

huangapple
  • 本文由 发表于 2017年4月12日 00:14:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/43351216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定