Golang模块管理让人抓狂
Golang模块管理让人抓狂 你好,我之前从未使用过GO,我想运行一个在GitHub上找到的脚本。
导入的包是:
“github.com/golang/leveldb/db” “github.com/golang/leveldb/table”
于是,我执行了:
go get github.com/golang/leveldb/db
这看起来没问题,但是:
go run script.go script.go:11:2: no required module provides package github.com/golang/leveldb/db: go.mod file not found in current directory or any parent directory; see ‘go help modules’ script.go:12:2: no required module provides package github.com/golang/leveldb/table: go.mod file not found in current directory or any parent directory; see ‘go help modules’
并且:
go list github.com/golang/leveldb no required module provides package github.com/golang/leveldb: go.mod file not found in current directory or any parent directory; see ‘go help modules’
我一定是在某些基本概念上理解有误,已经花了大约两个小时在网上搜索,但既无法解决这个问题,也无法理解我到底做错了什么。所以请帮帮我。
附注:我需要用[DOT]来替代点号,因为这个论坛很智能地把导入识别为URL,而我作为新用户只被允许发布两个链接。
更多关于Golang模块管理让人抓狂的实战教程也可以访问 https://www.itying.com/category-94-b0.html
你好,
你的目录里有 go.mod 文件吗?如果没有,你可以使用 go mod init [你的项目名称] 来生成它。go.mod 是用于跟踪项目依赖的文件,有了它之后,你就可以使用 go get ... 来获取包,或者,如果这些包已经作为导入语句写在代码里了,你可以运行 go mod tidy,它们就会自动为你下载。
你需要初始化一个Go模块。从Go 1.16开始,模块模式是默认启用的。错误信息提示在当前目录或任何父目录中找不到go.mod文件。
在你的项目目录中,运行以下命令来初始化模块:
go mod init your-module-name
例如,如果你的项目在/home/user/myproject目录下,你可以运行:
go mod init myproject
或者,如果你打算将代码发布到GitHub:
go mod init github.com/yourusername/myproject
然后再次尝试运行你的脚本:
go run script.go
Go会自动下载并管理所需的依赖项。
对于你提到的github.com/golang/leveldb包,需要注意的是这个包可能已经过时或不再维护。标准的LevelDB Go实现在github.com/syndtr/goleveldb。如果你的脚本确实需要github.com/golang/leveldb,初始化模块后,Go工具链会尝试获取它。
如果初始化模块后仍然遇到问题,可能是因为该包已经迁移或不存在。你可以检查go.mod文件是否包含正确的依赖,或者尝试使用替代的实现:
import (
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/table"
)
然后运行go mod tidy来自动更新依赖:
go mod tidy
这会扫描你的代码并更新go.mod文件,添加缺失的模块或移除未使用的模块。

