如何获取地址以使用反射字段?

huangapple go评论71阅读模式
英文:

How to get address to use reflect field?

问题

我得到了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 <- 希望得到与上面一行相同的值(地址)。\n", f)
}

我尝试调用UnsafeAddr、Addr等方法,但是我无法得到期望的值。

英文:

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

package main

import (
	&quot;fmt&quot;
	&quot;reflect&quot;
)

type A struct {
	one   int
	two   int
	three int
}

func main() {
	a := &amp;A{1, 2, 3}
	fmt.Println(&amp;a.two)
	
	ap := reflect.ValueOf(a)
	av := ap.Elem()
	twoField := av.Field(1)
	
	f := twoField.UnsafeAddr()
	fmt.Printf(&quot;%v &lt;- want to the same value(address) as the line above.\n&quot;, f)
}

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

答案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 以十六进制打印,前缀为 '0x' 以强调它
    fmt.Printf("0x%x", f)
}

可以随意测试它

英文:

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 (
    &quot;fmt&quot;
    &quot;reflect&quot;
)

type A struct {
    one   int
    two   int
    three int
}

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

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

    f := twoField.UnsafeAddr()
    // %x prints as hexadecimal, prefixing with &#39;0x&#39; to emphasize it
    fmt.Printf(&quot;0x%x&quot;, f)
}

Feel free to test it.

huangapple
  • 本文由 发表于 2013年10月28日 23:43:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/19639140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定