【问题标题】:Access address of Field within Structure variable in GolangGolang中Structure变量中Field的访问地址
【发布时间】:2017-06-26 02:35:13
【问题描述】:

如何在 GOLANG 中访问 STRUCTURE 中的 FIELD 指针或地址。我有整个结构变量的地址或指针,但无法正确访问结构内字段的地址。到目前为止,我已经尝试过反射,但似乎在某个地方坏了。非常感谢任何帮助。

【问题讨论】:

    标签: pointers go


    【解决方案1】:

    例如,

    package main
    
    import (
        "fmt"
    )
    
    type S struct{ F1, F2 int }
    
    func main() {
        s := new(S)
        f1, f2 := &s.F1, &s.F2
        fmt.Printf("%p %p %p\n", s, f1, f2)
    }
    

    输出:

    0x1040a128 0x1040a128 0x1040a12c
    

    【讨论】:

    • 谢谢分享。它看起来很简单,但在我的代码 final.id = &(intermediate.ID()) 中失败了。 final 中的 id 字段是一个字符串 *,而 intermediate.ID() 返回一个字符串。目前我必须创建一个临时变量来保存 middle.ID() 值,然后分配它的地址。我希望避免使用临时变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多