Adding and Updating Dependencies
Svep för att visa menyn
When you import a new package in your Go project, Go does not automatically fetch it. Instead, Go waits until you explicitly request dependency resolution. The most common ways to do this are by running go mod tidy or go get. When you import a package in your code and then run go mod tidy, Go examines your source files, identifies any imported packages not currently listed in your go.mod, and then downloads the required modules. It also removes unused dependencies from the module files. Alternatively, you can use go get to add a specific dependency or update an existing one. Both commands update your go.mod file to include the new dependency, and your go.sum file to record checksums for all downloaded modules, ensuring the integrity of your dependencies.
main.go
go.mod
go.sum
1234567891011package main import ( "fmt" "github.com/fatih/color" ) func main() { color.Red("This is a red message!") fmt.Println("Normal message.") }
Go modules use semantic versioning to manage dependencies. Semantic versioning follows the format vMAJOR.MINOR.PATCH, such as v1.15.0. When you add a dependency using go get, you can specify an exact version, a branch, or even a commit hash. For example, running go get github.com/fatih/color@v1.15.0 will add version 1.15.0 of the color package to your project. If you do not specify a version, Go will fetch the latest compatible version according to your current requirements and constraints in go.mod. This approach ensures that your builds are repeatable and that the same versions are used each time, unless you explicitly update them.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal