我们可以使用 go 进行模块的通用导入吗?更清楚地说,这里是用例:
package main
import (
"fmt"
"net/http"
)
json handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "you requested", r.URL.Path)
}
func main() {
var moduleName String = "/path/to/module"
import moduleName
http.HandleFunc("/", handler)
http.ListenAndServe(":8000", nil)
}
所以在 main 中你可以看到我正在尝试导入 moduleName,但这给了我一个错误。
是否有一些解决方法?
最佳答案
Go 是一种静态编译语言,而不是像 Python 那样的解释型语言。您的导入发生在编译时,而不是运行时。所以简而言之,不,你只能在包级别导入东西。
官方定义很清楚:
An import declaration states that the source file containing the declaration depends on functionality of the imported package and enables access to exported identifiers of that package.
关于导入还有一个有趣的注意事项是如果一个包被导入并且有一个init()
函数,这个函数将在程序启动时被调用来初始化包;来自文档:
If a package has imports, the imported packages are initialized before initializing the package itself
这为动态初始化留下了一些空间,但与动态导入相去甚远。
关于去导入模块 "later",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23784935/