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)
}
I got the following output:
Why is there no Blog struct and how to get the value of the 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
", results)
blogPointer := results[0]
fmt.Printf("%#v
", blogPointer)
blogValue := blogPointer.Elem()
fmt.Printf("%#v
", blogValue)
nameFieldValue := blogValue.FieldByName("Name")
fmt.Printf("%#v
", nameFieldValue)
name := nameFieldValue.String()
fmt.Println(name)
}
first we call the function returned by the interface and then we can fetch its value using Elem() method call to the pointer to interface
package main
import (
"fmt"
"reflect"
)
// Blog struct to hold the name of the author
type Blog struct {
Name string
}
//Test functon to to test the blog name
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")
res := m.Call(nil)
ptr := res[0]
fieldValue := ptr.Elem().FieldByName("Name").String()
fmt.Println(fieldValue)
}