是否可以false在go中区分和未设置的布尔值?
例如,如果我有这段代码
type Test struct {
Set bool
Unset bool
}
test := Test{ Set: false }
Run Code Online (Sandbox Code Playgroud)
是否有任何差别之间test.Set以及test.Unset如果是的话我怎么能告诉他们分开?
不,布尔有两种可能性:true或false。未初始化的布尔值的默认值为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
Run Code Online (Sandbox Code Playgroud)
这样做的代价是将值设置为文字有点麻烦,并且在使用值时必须更小心地取消引用(并检查nil)。