检查Go中是否设置了布尔值

问题描述 投票:0回答:5

是否可以区分

false
和 go 中未设置的布尔值?

例如,如果我有这个代码

type Test struct {
    Set bool
    Unset bool
}

test := Test{ Set: false }

test.Set
test.Unset
之间有什么区别吗?如果有的话我该如何区分它们?

go boolean
5个回答
24
投票

不,布尔值有两种可能:

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)。

游乐场链接


3
投票

bool
false
的值为零,因此它们之间没有区别。

请参阅规范的零值部分。

您想要解决什么问题需要进行此类检查?


2
投票

您可能会考虑使用三态布尔值:https://github.com/grignaak/tribool


0
投票

是的。您必须使用

*bool
而不是原始
bool


0
投票

不,你不能。或者您可以使用

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
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.