是否可以区分
false
和 go 中未设置的布尔值?
例如,如果我有这个代码
type Test struct {
Set bool
Unset bool
}
test := Test{ Set: false }
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
这样做的代价是,将值设置为文字有点难看,并且在使用这些值时必须更加小心地取消引用(并检查 nil)。
您可能会考虑使用三态布尔值:https://github.com/grignaak/tribool
是的。您必须使用
*bool
而不是原始 bool
不,你不能。或者您可以使用
iota
package main
import "fmt"
type Status int
const (
Unset Status = iota
Active
InActive
)
func (s Status) String() string {
switch s {
case Active:
return "active"
case InActive:
return "inactive"
default:
return "unset"
}
}
func main() {
var s Status
fmt.Println(s) // unset
s = Active
fmt.Println(s) // active
}