在结构体中引用布尔值进行赋值[重复]

问题描述 投票:0回答:1
type MyStruct struct {

    IsEnabled *bool
}

如何更改 *IsEnabled = true 的值

这些都不起作用:

*(MyStruct.IsEnabled) = true
*MyStruct.IsEnabled = true
MyStruct.*IsEnabled = true
go
1个回答
17
投票

您可以通过将 true 存储在内存位置然后访问它来完成此操作,如下所示:

type MyStruct struct {
    IsEnabled *bool
}


func main() {
    t := true // Save "true" in memory
    m := MyStruct{&t} // Reference the location of "true"
    fmt.Println(*m.IsEnabled) // Prints: true
}

来自文档

布尔型、数字型和字符串型的命名实例是 预先声明的。复合类型——数组、结构体、指针、函数、 接口、切片、映射和通道类型——可以使用类型来构造 文字。

由于布尔值是预先声明的,因此您无法通过复合文字创建它们(它们不是复合类型)。类型

bool
有两个
const
true
false
。这排除了以这种方式创建文字布尔值:
b := &bool{true}
或类似的方式。

应该注意的是,将 *bool 设置为

false
相当容易,因为
new()
会将 bool 初始化为该值。因此:

m.IsEnabled = new(bool)
fmt.Println(*m.IsEnabled) // False
© www.soinside.com 2019 - 2024. All rights reserved.