gopointer-address

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.


Solution

  • 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.