英文:
Load package dynamically
问题
在运行时加载特定的包是可能的吗?我想要一种插件机制,每个插件都具有相同的函数,但行为不同,根据配置文件的不同,加载其中的一个或另一个插件。
英文:
Is it possible to load a specific package during runtime?
I want to have a kind of plugins where each one has the same functions than the others but with different behaviour, and depending on the configuration file, load one or other.
答案1
得分: 40
不,Go语言不支持动态加载库。
你最好的选择是将插件作为独立的可执行文件启动,并通过套接字或标准输入/输出与其通信。
2017年更新
这个答案已经不再准确,Go现在支持插件(截至2021年6月,仅支持Linux和MacOS)。
英文:
No, Go doesn't support dynamically loaded libraries.
Your best bet is to start the plugin as its own executable and communicate with it through sockets or via stdin/stdout.
2017 update
This answer is no longer true, Go now supports plugins (for Linux and MacOS only as of June 2021)
答案2
得分: 27
现在已经支持这个功能,从Go 1.8版本开始。
https://golang.org/pkg/plugin/
答案3
得分: 19
你可以考虑在运行时执行“plugin”包,通过编写一个新的程序(比如,写入一个临时目录)并通过exec.Command执行,类似于exec.Command("go", "run", files...).Run()
。
你可以在这里看到一些类似的代码。
英文:
You might consider executing the ‘plugin’ packages at runtime, by writing out a new program (say, to a temp directory) and executing via exec.Command, something along the lines of exec.Command("go", "run", files…).Run()
You’ll see some similar code here.
答案4
得分: 0
只需执行以下操作:创建一个读取配置的代码生成器,生成一个基本的Go文件,按顺序加载包,然后执行该文件。编译型语言不支持动态加载,即使是Dart也有一定的限制。简单来说,只需读取配置文件,然后创建一个临时文件,其中包含必要的代码来加载并与套接字或HTTP进行通信。
英文:
Just do these,create a codegen that reads the configuration, generates a basic go file with the packages loaded in order and then execute that, compile languages won't nor provide dynamic loading, even dart suffers in a way,simple just read your configuration file then create a temporary file with the necessary codes to load up and communicate with sockets or http
答案5
得分: -4
我认为你正在寻找的是特殊函数init
。
如果你在一个包内添加如下代码:
func init() {
}
它将在该包第一次被导入时运行。
这仅在同一个二进制文件中发生。正如其他人已经提到的,Go语言不支持动态加载库。
英文:
I think what you are looking for is the special function init
if you add a
func init() {
}
inside a package it will run it the first time the package is imported.
This happens only in the same binary. As other have already said go does not support dynamically loaded libraries.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论