There is func someFunc(v interface{}, fn interface{})
where v
is a pointer to struct (say *A
) and fn is a method expression (say (*A).method()
). How to call fn
with v
as parameter (using reflect
)?

调用以指针作为接收者的指针的方法表达式
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- douduanque5850 2018-01-30 10:39关注
It's possible to do with
reflect.Value.Call()
, however it's pretty cumbersome, especially if you need to do something with the return value. But here's a basic example:package main import ( "fmt" "reflect" ) type Foo struct { Bar string } func concrete(foo *Foo) { fmt.Printf("Foo: %#v ", foo) } func someFunc(v interface{}, fn interface{}) { f := reflect.ValueOf(fn) arg := reflect.ValueOf(v) f.Call([]reflect.Value{arg}) } func main() { foo := Foo{"Bar"} someFunc(&foo, concrete) } // Output: Foo: &main.Foo{Bar:"Bar"}
https://play.golang.org/p/ED6QdvENxti
If you want to call a method of a struct by name, we need to revise it just a bit:
type Foo struct { Bar string } func (f *Foo) Concrete() { fmt.Printf("Foo: %#v ", f) } func callByName(v interface{}, fn string) { arg := reflect.ValueOf(v) f := arg.MethodByName(fn) f.Call([]reflect.Value{}) } func main() { foo := Foo{"Bar"} callByName(&foo, "Concrete") }
Notice that in this case the method value is already bound to the struct instance, so we don't need to pass it anything as an argument.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报