简体   繁体   中英

How to get address to use reflect field?

I got address of a.two.
I want to get same address to use reflect field.

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)
}

I tried to call UnsafeAddr, Addr, ... but, I couldn't get expects value.

You have the right address, it is just not in the right format.

If you convert it to hexadecimal, you get what you want:

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)
}

Feel free to test it .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM