dpi74187 2011-11-12 09:26
浏览 68
已采纳

在Go中通过名称调用结构及其方法?

I have found a function call MethodByName() here http://golang.org/pkg/reflect/#Value.MethodByName but it's not exactly what I want! (maybe because I don't know how to use it ... I cannot find any example with it). What I want is:

type MyStruct struct {
//some feilds here
} 
func (p *MyStruct) MyMethod { 
    println("My statement."); 
} 

CallFunc("MyStruct", "MyMethod"); 
//print out "My statement." 

So I guess, first I need something like StructByName() and after that use it for MethodByName(), is that right!?

  • 写回答

3条回答 默认 最新

  • dsstjqsr631426 2011-11-12 17:49
    关注

    To call a method on an object, first use reflect.ValueOf. Then find the method by name, and then finally call the found method. For example:

    package main
    
    import "fmt"
    import "reflect"
    
    type T struct {}
    
    func (t *T) Foo() {
        fmt.Println("foo")
    }
    
    func main() {
        var t T
        reflect.ValueOf(&t).MethodByName("Foo").Call([]reflect.Value{})
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集