英文:
Reference a boolean for assignment in a struct
问题
如何将 *IsEnabled 的值更改为 true?
以下方法都不起作用:
*(MyStruct.IsEnabled) = true
*MyStruct.IsEnabled = true
MyStruct.*IsEnabled = true
英文:
type MyStruct struct {
IsEnabled *bool
}
How do I change value of *IsEnabled = true
None of these work:
*(MyStruct.IsEnabled) = true
*MyStruct.IsEnabled = true
MyStruct.*IsEnabled = true
答案1
得分: 16
你可以通过将true存储在内存位置中,然后按照下面的方式访问来实现:
type MyStruct struct {
IsEnabled *bool
}
func main() {
fmt.Println("Hello, playground")
t := true // 将true保存在内存中
m := MyStruct{&t} // 引用true的位置
fmt.Println(*m.IsEnabled) // 输出:true
}
根据文档:
布尔、数值和字符串类型的命名实例是预声明的。可以使用类型字面量构造复合类型,如数组、结构体、指针、函数、接口、切片、映射和通道类型。
由于布尔值是预声明的,因此无法通过复合字面量创建它们(它们不是复合类型)。类型bool
有两个const
值true
和false
。因此,无法通过以下方式创建字面量布尔值:b := &bool{true}
或类似方式。
值得注意的是,将*bool设置为false
要简单得多,因为new()
会将bool初始化为该值。因此:
m.IsEnabled = new(bool)
fmt.Println(*m.IsEnabled) // 输出:false
英文:
You can do this by storing true in a memory location and then accessing it as seen here:
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
}
From the docs:
> Named instances of the boolean, numeric, and string types are
> predeclared. Composite types—array, struct, pointer, function,
> interface, slice, map, and channel types—may be constructed using type
> literals.
Since boolean values are predeclared, you can't create them via a composite literal (they're not composite types). The type bool
has two const
values true
and false
. This rules out the creation of a literal boolean in this manner: b := &bool{true}
or similar.
It should be noted that setting a *bool to false
is quite a bit easier as new()
will initialize a bool to that value. Thus:
m.IsEnabled = new(bool)
fmt.Println(*m.IsEnabled) // False
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论