英文:
Check if boolean value is set in Go
问题
在Go语言中,可以区分false
和未设置的布尔值吗?
例如,如果我有以下代码:
type Test struct {
Set bool
Unset bool
}
test := Test{ Set: false }
test.Set
和test.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类型有两种可能的取值:true
或false
。未初始化的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)。
英文:
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.
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论