是否可以区分 false
和 go 中未设置的 boolean 值?
例如,如果我有这段代码
type Test struct {
Set bool
Unset bool
}
test := Test{ Set: false }
test.Set
和 test.Unset
之间有区别吗?如果有,我该如何区分它们?
最佳答案
不, boolean 值有两种可能性:true
或 false
。未初始化的 boolean 值的默认值为 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)。
关于go - 检查是否在 Go 中设置了 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43351216/