去导入模块 "later"

标签 go

我们可以使用 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/

相关文章:

postgresql - 更新并返回GORM

html - 使用与存储桶 key 不同的文件名下载 S3 文件

golang test spy 错误地比较相等性

security - 如何在 Golang 二进制文件中混淆变量、函数和包名称的字符串?

go - golang 的手册页?

go - 如何获取 golang proto 生成的复杂结构中的所有字段名称

go - 关闭缓冲 channel 时是否应该排空它

Go Webapp 的 Dockerfile 目录结构

go - 声明go服务器的ServeHTTP方法

go - 如何获取目录总大小?