Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.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
Pointers reflect如何获取返回的结构指针_Pointers_Go_Struct_Reflection - Fatal编程技术网

Pointers reflect如何获取返回的结构指针

Pointers reflect如何获取返回的结构指针,pointers,go,struct,reflection,Pointers,Go,Struct,Reflection,我得到了以下输出: 这是测试方法 [] 为什么没有Blog结构以及如何获取Blog名称的值 package main import ( "fmt" "reflect" ) type Blog struct { Name string } func (blog *Blog) Test() (*Blog){ fmt.Println("this is Test method") blog.Name = "robin" return blog }

我得到了以下输出:

  • 这是测试方法
  • []
为什么没有Blog结构以及如何获取Blog名称的值

package main

import (
    "fmt"
    "reflect"
)

type Blog struct {
    Name string
}

func (blog *Blog) Test() (*Blog){
    fmt.Println("this is Test method")
    blog.Name = "robin"
    return blog
}

func main() {
    var o interface{} = &Blog{}
    v := reflect.ValueOf(o)
    m := v.MethodByName("Test")
    rets := m.Call([]reflect.Value{})
    fmt.Println(rets)
}


首先调用接口返回的函数,然后使用Elem()方法调用接口指针获取其值

package main

import (
    "fmt"
    "reflect"
)

type Blog struct {
    Name string
}

func (blog *Blog) Test() *Blog {
    fmt.Println("this is Test method")
    blog.Name = "robin"
    return blog
}

func main() {
    rv := reflect.ValueOf(&Blog{})
    rm := rv.MethodByName("Test")

    results := rm.Call(nil)
    fmt.Printf("%#v\n", results)

    blogPointer := results[0]
    fmt.Printf("%#v\n", blogPointer)

    blogValue := blogPointer.Elem()
    fmt.Printf("%#v\n", blogValue)

    nameFieldValue := blogValue.FieldByName("Name")
    fmt.Printf("%#v\n", nameFieldValue)

    name := nameFieldValue.String()
    fmt.Println(name)
}

首先我们调用接口返回的函数,然后我们可以使用Elem()方法调用接口指针来获取其值

package main

import (
    "fmt"
    "reflect"
)

type Blog struct {
    Name string
}

func (blog *Blog) Test() *Blog {
    fmt.Println("this is Test method")
    blog.Name = "robin"
    return blog
}

func main() {
    rv := reflect.ValueOf(&Blog{})
    rm := rv.MethodByName("Test")

    results := rm.Call(nil)
    fmt.Printf("%#v\n", results)

    blogPointer := results[0]
    fmt.Printf("%#v\n", blogPointer)

    blogValue := blogPointer.Elem()
    fmt.Printf("%#v\n", blogValue)

    nameFieldValue := blogValue.FieldByName("Name")
    fmt.Printf("%#v\n", nameFieldValue)

    name := nameFieldValue.String()
    fmt.Println(name)
}

Test
不返回任何内容。不要将
this
用作变量名。给你的接收者命名,使其具有某种意义。@tkausl如何从博客中获取名称值?@Flimzy如何从博客中获取名称值?@Flimzy这只是一个演示,我想使用反射调用相应的方法,并根据不同的结构类型获取它的值
Test
不返回任何内容。不要将
this
用作变量名。给你的接收者命名以表示某种意义。@tkausl我如何从博客中获取名称值?@Flimzy我如何从博客中获取名称值?@Flimzy这只是一个演示,我想使用反射调用相应的方法,并根据不同的结构类型获取其值谢谢你无私的奉献,我真的无法打开这个网站谢谢你无私的奉献,我真的无法打开这个网站