dongtuan5367 2018-01-30 10:23
浏览 35
已采纳

调用以指针作为接收者的指针的方法表达式

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)?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 三菱FX系列PLC串口指令
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型