Go 通过 包(目录中源文件的集合)和 模块(具有版本化依赖的包集合)来组织代码。这两者共同结构化项目并管理依赖。
包 — 相关代码的目录
go
main
mathutil
{ a + b }
{}
一个目录中的所有文件都属于一个包。大小写控制可见性:大写开头的名称是导出的(在包之间公开),小写的是包的私有。
import (
"fmt" // standard library
"strings"
"github.com/user/repo/mathutil" // a third-party or local module package
)
fmt.Println(strings.ToUpper("hi"))
mathutil.Add(2, 3) // use Exported names via package.Name
go mod init github.com/user/myapp # create a module → makes go.mod
go get github.com/gin-gonic/gin # add a dependency (records it in go.mod)
go mod tidy # add missing & remove unused dependencies
go build # build using the module's dependencies
go.mod — declares the module path, Go version, and direct dependencies (+ versions)
go.sum — cryptographic checksums of dependencies (integrity/security)
模块(在 Go 1.11 中引入)是依赖管理的单位 — go.mod 列出确切的依赖版本,使构建可重现。go.sum 验证依赖的完整性。
package main
func init() { // runs automatically when the package loads (before main)
// setup
}
func main() { // entry point of an executable (package main only)
}
myapp/
go.mod
main.go package main
internal/ packages here are PRIVATE to this module (can't be imported externally)
pkg/ or other dirs/ reusable packages
internal/ 目录很特殊 — 它的包只能在同一模块内导入,在模块级别强制实施封装。
包和模块是 Go 项目的结构方式,也是如何管理依赖的方式 — 对任何真实项目都至关重要。
理解包(文件的目录、基于大小写的导出/未导出可见性、特殊的 main 包)是组织代码和控制其公共 API 的基础。
模块(go mod、go.mod/go.sum)提供可重现的、版本化的、完整性检查的依赖管理 — 替代旧的 GOPATH 方法的现代标准。
了解导入系统、internal/ 约定用于模块私有代码,以及工具链(go mod init/tidy、go get)对于构建、共享和维护 Go 项目是必需的,反映了对 Go 生态系统的实践流利性。