Go / 系统课时

用 go mod init 创建模块

用 go mod init 创建模块

go mod init 把当前目录声明为一个 Go 模块,并生成依赖管理入口 go.mod。本篇用 Go 1.27 工具链创建一个最小模块,说明 module path 怎样决定本项目包的导入前缀,以及发布时为什么不能随意修改它。

学习目标

  • 用 go mod init 在正确目录创建 go.mod。
  • 根据仓库地址选择可发布的 module path,并判断项目内包的完整导入路径。
  • 验证当前模块根目录,并理解 Go 1.27 新模块默认的 go 版本行。

创建模块并检查 go.mod

先新建一个空目录并进入它。示例使用 example.com/acme/hello-service,它适合本地练习;真实公开项目应换成代码仓库对应的路径,例如 github.com/acme/hello-service。

bash
mkdir hello-service
cd hello-service
go version
go mod init example.com/acme/hello-service

预期输出

text
go version go1.27.<PATCH> <OS>/<ARCH>
go: creating new go.mod: module example.com/acme/hello-service

go mod init 会在当前目录写入 go.mod。Go 1.27 延续 Go 1.26 引入的默认策略:使用 1.27 工具链新建模块时,go 指令默认面向前一个稳定版本,因此文件通常是:

text
module example.com/acme/hello-service

go 1.26.0

这里的 go 行不是当前安装工具链的版本展示,而是模块声明的最低 Go 语言与模块语义版本。如果项目确实要使用 Go 1.27 才提供的语言特性,可显式提升:

bash
go mod edit -go=1.27.0
go list -m -f '{{.GoVersion}}'

预期输出

text
1.27.0

module path 决定项目内导入前缀

module example.com/acme/hello-service 相当于给模块内所有包设定统一前缀。包路径等于 module path 加上该包相对模块根目录的子目录。

目录 对应包导入路径
internal/httpapi example.com/acme/hello-service/internal/httpapi
pkg/clock example.com/acme/hello-service/pkg/clock
cmd/server example.com/acme/hello-service/cmd/server

例如代码从 cmd/server 导入 internal/httpapi 时,应写完整路径 example.com/acme/hello-service/internal/httpapi。如果以后把 module path 改成 github.com/acme/hello-service,项目内引用旧前缀的 import 也必须同步修改。

外部依赖不使用你的 module path 前缀。源码若导入 github.com/google/uuid,Go 会按该包所属模块解析版本,并在需要时把要求记录到 go.mod;校验信息通常写入 go.sum。

为发布选择稳定路径

准备发布时,module path 最好直接对应可被 Go 工具定位的仓库路径。仓库为 github.com/acme/hello-service 时,v0 和 v1 通常使用同名 module path;若发布不兼容的 v2,路径要带主版本后缀 github.com/acme/hello-service/v2。

只做本地练习且永不发布时,可以使用 example.com/... 或 example/... 这类教学路径;要发布时再从一开始使用最终仓库路径更省迁移成本。

验证模块根目录

创建完成后,用 Go 自己的命令确认当前 shell 实际命中了哪个 go.mod,比只看编辑器目录更可靠。

bash
go env GOMOD
go list -m

预期输出

text
<PATH>/hello-service/go.mod
example.com/acme/hello-service

如果 go env GOMOD 指向父目录的另一个 go.mod,说明你可能站在已有模块的子目录中。先切换到真正要作为模块根的目录,再决定是否创建新模块;无意间嵌套模块会让依赖解析和包导入边界变得不同。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

用 go mod init 创建模块

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通