0

我得到了a.two的地址。
我想获得相同的地址以使用反射字段。

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    one   int
    two   int
    three int
}

func main() {
    a := &A{1, 2, 3}
    fmt.Println(&a.two)

    ap := reflect.ValueOf(a)
    av := ap.Elem()
    twoField := av.Field(1)

    f := twoField.UnsafeAddr()
    fmt.Printf("%v <- want to the same value(address) as the line above.\n", f)
}

我试图调用 UnsafeAddr, Addr, ... 但是,我无法获得期望值。

4

1 回答 1

1

您有正确的地址,只是格式不正确。

如果你把它转换成十六进制,你会得到你想要的:

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    one   int
    two   int
    three int
}

func main() {
    a := &A{1, 2, 3}
    fmt.Println(&a.two)

    ap := reflect.ValueOf(a)
    av := ap.Elem()
    twoField := av.Field(1)

    f := twoField.UnsafeAddr()
    // %x prints as hexadecimal, prefixing with '0x' to emphasize it
    fmt.Printf("0x%x", f)
}

随意测试它

于 2013-10-28T15:54:55.023 回答