Go-指针指向布尔*bool的理性是什么? 问题:

Go-指针指向布尔*bool的理性是什么? 问题:,go,Go,请帮助理解Go中有指向布尔值的指针的原因是什么?为什么不在没有布尔指针的情况下直接指定true或false go中代码语句中的每个“真”“假”都需要存储吗 type GetItemInput struct { AttributesToGet []*string `min:"1" type:"list"` ConsistentRead *bool `type:"boolean"` <----- 相关的 将true存储在内存位置,然后访问它 默认情况下,在Go中初始化结

请帮助理解Go中有指向布尔值的指针的原因是什么?为什么不在没有布尔指针的情况下直接指定truefalse

go中代码语句中的每个“真”“假”都需要存储吗

type GetItemInput struct {
    AttributesToGet []*string `min:"1" type:"list"`
    ConsistentRead *bool `type:"boolean"` <-----
相关的
  • 将true存储在内存位置,然后访问它


默认情况下,在Go中初始化结构时,结构中的所有属性都将具有零值,因此对于类型为bool的属性,默认情况下它将包含值False

在您的代码中,如果您不希望该属性在默认情况下具有值True或False,除非您明确这样做,那么在这种情况下,您将创建属性*bool,以便在默认情况下它将包含nil

出于同样的原因,您不能直接将True或false赋值给该属性,首先您需要创建一个具有bool值的变量,并将该变量地址设置为该属性,如下所示

type MyStruct struct {
    IsEnabled *bool 
}

func main() {
    test := MyStruct{} // By default test.IsEnabled will contain value <nil>
    t := true // Save "true" in memory
    test.IsEnabled = &t // Reference the location of "true"
    fmt.Println(*test.IsEnabled) // Prints: true
}

默认情况下,在Go中初始化结构时,结构中的所有属性都将具有零值,因此对于类型为bool的属性,默认情况下它将包含值False

在您的代码中,如果您不希望该属性在默认情况下具有值True或False,除非您明确这样做,那么在这种情况下,您将创建属性*bool,以便在默认情况下它将包含nil

出于同样的原因,您不能直接将True或false赋值给该属性,首先您需要创建一个具有bool值的变量,并将该变量地址设置为该属性,如下所示

type MyStruct struct {
    IsEnabled *bool 
}

func main() {
    test := MyStruct{} // By default test.IsEnabled will contain value <nil>
    t := true // Save "true" in memory
    test.IsEnabled = &t // Reference the location of "true"
    fmt.Println(*test.IsEnabled) // Prints: true
}

你必须问问这段代码的作者。有时,这样做是为了区分已设置的bool(true或false)和未设置的bool(例如,在解组JSON期间)。对于您的代码,此原因不适用。可能作者想让它与其他字段保持一致,或者有其他原因。输出是JSON文档,作为字节列表。如果您更喜欢字符串,可以将打印作为字符串阅读。您必须询问此代码的作者。有时,这样做是为了区分已设置的bool(true或false)和未设置的bool(例如,在解组JSON期间)。对于您的代码,此原因不适用。可能作者想让它与其他字段保持一致,或者有其他原因。输出是JSON文档,作为字节列表。如果您更喜欢字符串作为字符串读取打印。
fmt.Println(*m.IsEnabled)
应该是
fmt.Println(*test.IsEnabled)
?类似于?
fmt.Println(*m.IsEnabled)
应该是
fmt.Println(*test.IsEnabled)
?类似
type MyStruct struct {
    IsEnabled *bool 
}

func main() {
    test := MyStruct{} // By default test.IsEnabled will contain value <nil>
    t := true // Save "true" in memory
    test.IsEnabled = &t // Reference the location of "true"
    fmt.Println(*test.IsEnabled) // Prints: true
}
fmt.Printf("%v", string(data))