type MyStruct struct {
IsEnabled *bool
}
Run Code Online (Sandbox Code Playgroud)
如何更改*IsEnabled = true的值
这些都不起作用:
*(MyStruct.IsEnabled) = true
*MyStruct.IsEnabled = true
MyStruct.*IsEnabled = true
Run Code Online (Sandbox Code Playgroud)
您可以通过将true存储在内存位置然后访问它来执行此操作,如下所示:
type MyStruct struct {
IsEnabled *bool
}
func main() {
fmt.Println("Hello, playground")
t := true // Save "true" in memory
m := MyStruct{&t} // Reference the location of "true"
fmt.Println(*m.IsEnabled) // Prints: true
}
Run Code Online (Sandbox Code Playgroud)
来自文档:
预先声明了布尔,数字和字符串类型的命名实例.可以使用类型文字构造复合类型 - 数组,结构,指针,函数,接口,切片,映射和通道类型.
由于布尔值是预先声明的,因此无法通过复合文字创建它们(它们不是复合类型).该类型bool有两个const值true和false.这排除了以这种方式创建文字布尔值:b := &bool{true}或类似.
应该注意的是,将bool设置为false更容易,因为new()将bool初始化为该值.从而:
m.IsEnabled = new(bool)
fmt.Println(*m.IsEnabled) // False
Run Code Online (Sandbox Code Playgroud)