drhs13583567608 2015-09-02 22:14
浏览 27
已采纳

引用布尔值以在结构中赋值

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条回答 默认 最新

  • doufu2396 2015-09-02 22:21
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大