Go
Beginner
1 min read
Working with Go Modules and Dependencies
Example
// go.mod example for a real project
// module github.com/example/webapp
//
// go 1.22
//
// require (
// github.com/gin-gonic/gin v1.10.0
// github.com/jmoiron/sqlx v1.4.0
// github.com/lib/pq v1.10.9
// )
// Common go mod commands:
// $ go mod init github.com/example/webapp — create a new module
// $ go mod tidy — add missing, remove unused deps
// $ go get github.com/gin-gonic/gin@latest — add/upgrade a dependency
// $ go get github.com/gin-gonic/gin@v1.9.0 — pin to a specific version
// $ go mod vendor — copy deps to ./vendor
// $ go mod verify — check dep checksums
// $ go list -m all — list all module dependencies
// Using an external package (after go mod tidy):
package main
import (
"fmt"
"sort"
"golang.org/x/exp/slices" // example external package
)
func main() {
// Using the standard library sort package
words := []string{"banana", "apple", "cherry", "date"}
sort.Strings(words)
fmt.Println("sorted:", words)
// golang.org/x/exp/slices provides generics-based helpers
nums := []int{5, 2, 8, 1, 9, 3}
slices.Sort(nums)
fmt.Println("sorted nums:", nums)
idx, found := slices.BinarySearch(nums, 8)
fmt.Printf("found 8 at index %d: %v\n", idx, found)
}