在结构体中引用一个布尔值进行赋值。

huangapple go评论84阅读模式
英文:

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有两个consttruefalse。因此,无法通过以下方式创建字面量布尔值: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

huangapple
  • 本文由 发表于 2015年9月3日 06:14:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/32364027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定