go - 检查是否在 Go 中设置了 boolean 值

标签 go boolean

是否可以区分 false 和 go 中未设置的 boolean 值?

例如,如果我有这段代码

type Test struct {
    Set bool
    Unset bool
}

test := Test{ Set: false }

test.Settest.Unset 之间有区别吗?如果有,我该如何区分它们?

最佳答案

不, boolean 值有两种可能性:truefalse。未初始化的 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)。

Playground link

关于go - 检查是否在 Go 中设置了 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43351216/

相关文章:

MySQL 查询过滤包含搜索字符串中任何单词的记录

iphone - 在 objective-c 中使用 BOOL 变量时发出警告

json - 如何在对象具有字符串键的 Golang 中解码 JSON

pointers - 在 golang 的嵌套结构中使用指针的好处

groovy - 如何在groovy中将 boolean 值(真或假)转换为字符串值?

c++ - double not (!!) 用于非 boolean 变量有什么作用?

go - LiteIDE 在您保存时删除导入

go - Go slice 索引符号背后的想法是什么?

go - Prometheus Exporter - 直接检测与自定义收集器

c++ cin only boolean(0,1)