Dynamic loading in Golang?

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

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:

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:

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).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!