如何从Go中的字符串路径导入包? [英] How to import package by path from string in Go?
问题描述
我有一个包名称的字符串(比如my / package / test),我想导入它并从包中调用一些函数。
类似于这:
func init(){
var pkg string =test / my / pkg
import pkg
pkg.Test()
}
PS。感谢您的帮助
Go语言不允许您在示例中提到的内容。这是一个有意识的选择。在我看来,这种选择背后的原因与编译器的性能以及机器对代码的理解容易性有关。例如,这可以启用 gofix 等工具,可以部分修复Go代码,而无需用户干预。
它还使程序员能够清楚地看到该程序使用的所有静态导入的软件包。
另请参阅Go语言规范中的源文件组织的语法规则。
关于在运行时动态加载包:Go在运行时不支持加载包。未来的Go运行时可能会实现此功能(例如,它偶尔会在golang-nuts邮件列表中的邮件中被请求),但目前状态是不支持此功能。
I have a string with name of package (like "my/package/test") and I wanna import that and call some function from package.
Something like this:
func init() {
var pkg string = "test/my/pkg"
import pkg
pkg.Test()
}
PS. Thanks for help
The Go language does not allow what you mentioned in your example. This is a conscious choice. In my opinion, the reason behind this choice has to do with compiler performance and ease of code understanding by the machine. This for example enables tools such as gofix that can partially fix Go code without need for user intervention.
It also enables a programmer to clearly see all of the statically imported packages used by the program.
See also the grammar rules for source file organization in the Go language specification.
In relation to dynamically loading packages at run-time: Go has no support for loading packages at run-time. A future Go run-time might implement this feature (for example, it is occasionally being requested in messages in the golang-nuts mailing list), but the current state is that there is no support for this feature.
这篇关于如何从Go中的字符串路径导入包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!