Go:按名称查找函数 [英] Go: lookup function by name

查看:329
本文介绍了Go:按名称查找函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  package main 

func test(){
print(In Test)
}

func main(){
a:=test$ b $您可能会收到一封电子邮件,您可能会收到一封电子邮件给您,您可能会收到一封电子邮件,更好的答案,如果你说你想要实现的,因为反射通常不是最好的方式。但如果函数是类型上的方法(反映将有所帮助/ net / rpc /> net / rpc 是一个此示例)。

 包main 

import(
fmt
反映


类型T struct {}

func(T)Add(x,y int)int {
return x + y
}

func main(){
t:= reflect.ValueOf(T {})
m:= t.MethodByName )
args:= [] reflect.Value {reflect.ValueOf(1),reflect.ValueOf(2)}
fmt.Println(m.Call(args)[0] .Int )
}


$ b如果你想知道godoc 工作,他们解析源代码而不使用反射。



编辑:游乐场版本


I am new to type safe, and can't figure out how to do following

package main

func test(){
    print("In Test")
}

func main(){
    a := "test"
    a()
}

解决方案

You might get better answers if you state what you're trying to achieve, as reflection is usually not the best way. But reflect will help if the functions are methods on a type (net/rpc is an example of this).

package main

import (
    "fmt"
    "reflect"
)

type T struct {}

func (T) Add(x, y int) int {
    return x + y
}

func main() {
    t := reflect.ValueOf(T{})
    m := t.MethodByName("Add")
    args := []reflect.Value{reflect.ValueOf(1), reflect.ValueOf(2)}
    fmt.Println(m.Call(args)[0].Int())
}

If you were wondering how tools like godoc work, they parse the source rather than use reflection.

Edit: Playground version

这篇关于Go:按名称查找函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆