Go splits code into packages and groups packages into versioned modules. This chapter covers go.mod and go.sum, visibility, dependencies, go install, and vendoring.
Modules: go.mod and go.sum
A module is a collection of packages that are released and versioned together. Its definition is the go.mod file at the module root, which records the module path, the Go language version the module targets, and the other modules it depends on.
module example.com/shop
go 1.xx // filled in by go mod init from your installed toolchain
require (
github.com/google/uuid v1.6.0
golang.org/x/sync v0.7.0 // indirect
)
The // indirect marker means your code does not import that module directly; something you depend on needs it. Treat the version numbers above as placeholders, since the tooling fills in real ones. Alongside go.mod sits go.sum, which stores cryptographic checksums of every module version you have downloaded. The go command verifies downloads against these hashes and, by default, against the public checksum database at sum.golang.org. Commit both files.
Packages and visibility
Each directory is one package, and its import path is the module path followed by the directory path. Visibility is controlled by capitalization alone: an identifier starting with an uppercase letter is exported and usable from other packages, while a lowercase one is private to its package. The rule applies uniformly to functions, types, variables, constants, struct fields, and methods.
// file: greet/greet.go
package greet
import "fmt"
// Hello is exported. Doc comments on exported names start with the name.
func Hello(name string) string {
return fmt.Sprintf("%s, %s!", prefix(), name)
}
// prefix is visible only inside package greet.
func prefix() string { return "Hello" }
type Config struct {
Lang string // exported field
debug bool // unexported field
}
// file: main.go
package main
import (
"fmt"
"example.com/shop/greet"
)
func main() {
fmt.Println(greet.Hello("gopher"))
// greet.prefix() would not compile: it is unexported
}
Name packages with a short, lowercase word, and remember that callers always see the package name in front: greet.Hello reads well, while greet.GreetHello stutters. Import cycles, where package A imports B and B imports A, are rejected by the compiler. For packages that should only be shared within your own module, use the internal directory introduced in the first chapter.
Adding and upgrading dependencies
To use a third-party package, import it in your code and run go get or go mod tidy. tidy adds whatever your code imports and drops modules that nothing uses anymore, so it is a good habit to run it before committing.
0 commentaire
Se connecter · Connectez-vous pour laisser un commentaire.