今日已更新 287 条资讯 | 累计 20259 条内容
关于我们

Go Packages and Modules explained

Fer Rios 2026年06月11日 08:37 6 次阅读 来源:Dev.to

What is a package? In Go, every Go program is made up of packages. A package is a directory of .go files that share the same package declaration. The primary purpose of packages is to help you isolate and reuse code. myapp/ ├── main.go ← package main └── math/ ├── add.go ← package math └── sub.go ← package math Both add.go and sub.go declare package math. They can call each other's functions directly, no import needed within the same package. Inside a package, every .go file should begin with a package {name} statement which indicates the name of the package that the file is a part of. Every exported identifier (capitalized name) in that directory is accessible to anyone who imports the package. Here's what that looks like in practice: // math/add.go package math // pi is an unexported variable. var pi = 3.14159 // Add returns the sum of two integers. // Exported — starts with a capital letter. func Add ( a , b int ) int { return a + b } // math/sub.go package math // Exported — starts with a capital letter. func Subtract ( a , b int ) int { return a - b } // main.go package main import ( "fmt" "github.com/yourname/myapp/math" ) func main () { fmt . Println ( math . Add ( 3 , 4 )) // 7 fmt . Println ( math . Subtract ( 10 , 3 )) // 7 // fmt.Println(math.pi) — compile error: unexported } Two rules to remember: Capital letter = exported (public). Lowercase = unexported (private to the package). One package per directory. One directory per package. What is a module? If a package is a folder, a module is the whole project, a tree of packages with a name, a Go version requirement, and a list of external dependencies. When you start a Go project, you create a module, and inside that module, there will be packages. Every Go project has exactly one go.mod file at its root. That file defines the module. Here's what a real one looks like: module github . com / yourname / weather - cli go 1.21 require ( github . com / aws / aws - sdk - go - v2 v1 .24.0 github . com / aws / aws

本文内容来源于互联网,版权归原作者所有
查看原文