Go / 系统课时
用 go mod init 建立模块
用 go mod init 建立模块
新建 Go 项目时,先建立 Module,才能让 Go 明确项目的模块路径和依赖边界。本篇从一个最小程序开始,执行 go mod init,检查生成文件,并验证 module path 如何对应代码中的导入路径。
学习目标
- 能为新的 Go 项目创建
go.mod - 理解
module声明与目录位置、导入路径的关系 - 能判断本地包为什么应该使用模块路径进行导入
创建第一个 Go Module
先准备一个空目录,例如 hello-module,然后进入目录执行:
mkdir hello-module
cd hello-module
go mod init example.com/hello-module预期输出:
go: creating new go.mod: module example.com/hello-module执行后目录中会出现 go.mod。它至少声明当前模块的路径,内容类似:
module example.com/hello-module这里的 example.com/hello-module 不是必须真实存在的网站地址。它首先是模块的身份标识,实际项目通常使用仓库地址、公司内部模块路径或其他稳定的唯一路径。
module path 为什么重要
假设模块目录下有一个子包 greet:
hello-module/
├── go.mod
├── main.go
└── greet/
└── greet.go在 main.go 中导入子包时,应使用 module 声明加上子目录:
package main
import (
"fmt"
"example.com/hello-module/greet"
)
func main() {
fmt.Println(greet.Message())
}greet/greet.go:
package greet
func Message() string {
return "hello from module"
}此时从模块根目录运行:
go run .预期输出:
hello from module导入路径并不是根据当前磁盘绝对路径自动生成的,而是由 go.mod 中的 module 路径作为前缀确定。也就是说,如果把 module 改成 corp.example/team/hello-module,这个子包的导入路径也应改成 corp.example/team/hello-module/greet。
什么时候执行 go mod init
通常在“这是一个新的独立 Go Module”时执行一次。例如新建服务、命令行工具或可复用库,都可以从项目根目录开始初始化。
不要在已经存在有效 go.mod 的子目录里随意再次执行 go mod init。那通常意味着你正在创建嵌套模块,依赖边界会发生变化;除非你明确需要多个独立模块,否则应先确认目录结构。
创建模块后,最重要的检查不是“文件是否生成”,而是确认 module 路径稳定、源码导入路径一致。这样后面添加第三方依赖或拆分内部包时,Go 才能沿着明确的模块边界解析代码。