在Go语言中,能否区分false和未设置的布尔值?
例如,如果我有以下代码:
type Test struct {
Set bool
Unset bool
}
test := Test{ Set: false }
test.Set
和test.Unset
之间有什么区别,如果有的话,我该如何区分它们?
在Go语言中,能否区分false和未设置的布尔值?
例如,如果我有以下代码:
type Test struct {
Set bool
Unset bool
}
test := Test{ Set: false }
test.Set
和test.Unset
之间有什么区别,如果有的话,我该如何区分它们?
不,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)。
是的。您必须使用*bool
而不是原始的bool