使用反射执行不同包的函数,步骤如下:

  1. 导入 reflect 包和要执行的函数所在的包。
import (
    'reflect'
    'your/package/path'
)
  1. 获取函数的 reflect.Value 对象。
funcValue := reflect.ValueOf(path.YourFunction)
  1. 创建参数列表,如果函数有参数的话。
args := []reflect.Value{
    reflect.ValueOf(arg1),
    reflect.ValueOf(arg2),
}
  1. 调用函数的 Call 方法,并传递参数列表。
result := funcValue.Call(args)
  1. 获取函数的返回值。
returnValue := result[0].Interface()

完整示例代码如下:

package main

import (
    'fmt'
    'reflect'
    'your/package/path'
)

func main() {
    funcValue := reflect.ValueOf(path.YourFunction)
    args := []reflect.Value{
        reflect.ValueOf(arg1),
        reflect.ValueOf(arg2),
    }
    result := funcValue.Call(args)
    returnValue := result[0].Interface()

    fmt.Println(returnValue)
}
Go 反射:跨包调用函数

原文地址: https://www.cveoy.top/t/topic/lpNG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录