Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 如何获取地址以使用反射字段?_Go_Pointer Address - Fatal编程技术网

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

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.

我得到了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.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)
}
请随意