英文:
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 (
"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.
答案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 (
"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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论