Packages and Module

Go, packages and modules serve distinct but related roles in organizing and managing code
Module(Big, Complete Project) Package(Small)
What Entire project is a Go module, managed by the go.mod file. This is Collection of Go packages A directory is automatically considered a package by Go. So package is directory containing 1 or more Go source files. Every Go source file belongs to a package, declared at the beginning of the file using package `packagename`.
Creation

$ mkdir mymodule
$ cd mymodule
                        

Command creates a go.mod file that defines your module path & initializes it

$ go mod init mymodule
$ ls -ltr 
go.mod
$ cat go.mod
module mymodule

go 1.24.0
                        

// Create Package-1
$ mkdir mathdir; cd mathdir
$ vim math.go
package mathdir
func Add(a int, b int) int {
    return a + b
}

// Create Package-2
$ mkdir stringdir; cd stringdir
$ vim string.go
func Concat(a string, b string) string {
    return a + b
}

// Main Application accessing Packages
// main.go
package main
import (
    "fmt"
    "github.com/username/mymodule/mathdir"
    "github.com/username/mymodule/stringdir"
)
func main() {
    sum := mathdir.Add(5, 10)
    fmt.Println("Sum:", sum)

    concatenated := stringdir.Concat("Hello, ", "World!")
    fmt.Println("Concatenated String:", concatenated)
}

$ go run main.go
                    
Examples
Error Package Errors package is a standard package provided by go's standard library. It is used to create and manipulate errors in a consistent and idiomatic way

package main
import (
    "errors"
    "fmt"
)
func divide(a, b int) (int, error) {	//Function returning int AND error
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}
func main() {
    result, err := divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Result:", result)
}
                                        

import statement

import keyword is used to include external packages/modules in Go program.

import "fmt"
or
import (              //import multiple packages
    "fmt"
    "math"
)

// Use functions in package using dot statement
fmt.Println("Hello, world!")
            

go.mod file

List all externally hosted packages which require operation(like go get ).
When you run a command like `go get github.com/user/repo`, the Go tooling will fetch the module from that location

$ go.mod
/*Specifies the the module's path*/
module test

go 1.0

/*lists the specific versions of all dependencies required by the module
It helps ensure that the correct versions of dependencies are used
*/
require (
        github.com/auth0/go-jwt-middleware/v2 v2.2.1
)

require (
        github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
)
            

go.sum file

The go build command uses the Go module cache to find dependencies and will not automatically download dependencies if they are missing.
Once dependency is downloaded entry is created in go.sum file
When 1st time go.mod is modified, you need to run go mod download command to download the module and update the go.sum file

$ go.sum
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=

// Need to run after making entry in go.mod
go mod download github.com/shirou/gopsutil/v3

// Then run
go mod tidy
            

How to add external module to code?


$ main.go
package main
import (
    "github.com/shirou/gopsutil/v4/process"     //External module for psutil
)
func main() {
    ..
}

// 1. Go to documentation and find versions
// https://godocs.io/github.com/shirou/gopsutil/v4/process
// https://godocs.io/github.com/shirou/gopsutil/v4/process?view=versions (v4.24.6)

// 2. Add package path & version
$ go.mod
require (
    github.com/shirou/gopsutil/v4 v4.24.6
)

// 3. Run command to download and cache in go.sum
$ go mod download github.com/shirou/gopsutil/v4