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)
}
我得到了以下输出:
- 这是测试方法
- []
为什么没有 Blog 结构体,如何获取 Blog Name 的值?
最佳答案
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)
}
关于pointers - reflect如何获取返回的结构体指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47609731/