本文介绍了在Go中通过名称调用Struct及其方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里找到一个调用 MethodByName()的函数但它不完全是我想要的! (也许是因为我不知道如何使用它......我找不到任何示例)。我想要的是:

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." 

所以我想,首先我需要类似 StructByName(),然后用它作为 MethodByName(),是吗??

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

推荐答案

要在对象上调用方法,首先使用 reflect.ValueOf 。例如:

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{})
}

这篇关于在Go中通过名称调用Struct及其方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 18:17