Golang中的动态加载是什么意思?

huangapple go评论118阅读模式
英文:

Dynamic loading in Golang?

问题

我有一个常见项目和一些作为常见项目中连接器的小项目。

我想创建一个常见项目,这样当开发一个新的连接器时,我就不必修改常见项目中的代码。是否可以在Go中动态加载结构,只需知道结构和其文件夹的路径(通过将此路径放在常见项目的文件中,并在运行时加载该结构)?

connector1
  connector1.go
  /util
  /domain

connectorN
  connectorN.go 
  /domain

commonProject
   main.go
   config.ini

结构config.ini

Conector
name = connector1
path = ..../connector1/connector1.go

Conector
name = connectorN
path = ..../connectorN/connectorN.go

我知道在Java中可以使用以下代码实现这一点,但我正在尝试在Go中实现。有什么想法吗?

Class.forName(String) 

或者

ClassLoader.loadClass(String)
英文:

I've got a common project and small projects which act such as connectors in the common project.

I want to create a common project such that when a new connector is developed I don’t have to modify code in the common project. Is it possible to dynamically load the structures in Go, only knowing the path (by putting this path in a file in common project and at runtime load that struct) of the struct and its folders?

connector1
  connector1.go
  /util
  /domain

connectorN
  connectorN.go 
  /domain

commonProject
   main.go
   config.ini

Structure config.ini

Conector
name = connector1
path = ..../connector1/connector1.go

Conector
name = connectorN
path = ..../connectorN/connectorN.go

I know that this is possible to do this in Java with code like this, but I am trying to do this in Go. Any ideas?

Class.forName(String) 

or

ClassLoader.loadClass(String):

答案1

得分: 2

我可以看到两种实现你描述的方式,但请记住,正如 @icza 指出的那样,Go 生成的是静态二进制文件,所以无法动态加载外部库。

不过,你可以:

  • 使用 cgo 与 C 代码进行接口交互,并以这种方式加载外部库。
  • 使用 net/rpc 包使多个二进制文件相互通信,并按需加载它们。
英文:

I can see two ways to achieve what you describe, but keep in mind, as @icza pointed out, that go produces static binaries, so you can't load external libraries dynamically.

You can, however:

  • use cgo to interface with C code, and load external libraries that
    way.
  • use the net/rpc package to have several binaries communicate
    with each other, and load those on demand.

答案2

得分: 1

在Java中,类是在需要时动态加载的,当它们被使用或引用时。

Go生成静态链接的本机二进制文件,没有外部依赖,因此无法像Java中使用Class.forName()那样以某种方式加载新的“类型”或“函数”(至少不是用Go编写的代码)。

英文:

In Java classes are loaded dynamically, on demand, when they are used/referred to.

Go produces statically linked native binaries without external dependencies, so you can't load new "types" or "functions" in a way you can do in Java with the Class.forName() (at least not code written in Go).

huangapple
  • 本文由 发表于 2015年5月7日 17:47:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/30097451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定