Go 如何获取地址以使用反射字段?
我得到了a.2的地址。Go 如何获取地址以使用反射字段?,go,pointer-address,Go,Pointer Address,我得到了a.2的地址。 我想得到相同的地址以使用反射字段 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.
我想得到相同的地址以使用反射字段
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)
}
主程序包
进口(
“fmt”
“反映”
)
类型A结构{
一整型
两整数
三整数
}
func main(){
a:=&a{1,2,3}
fmt.Println(&a.2)
ap:=反射值(a)
av:=ap.Elem()
twoField:=平均字段(1)
f:=twoField.UnsafeAddr()
fmt.Printf(“%v您的地址正确,只是格式不正确
如果将其转换为十六进制,则可以得到所需的:
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)
}
请随意