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 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络