Golang: Import Local Packages
Feb 24, 2023
import “<module_name>/<package_name>
Project Structure
<project_name>
├── main.go
└── <package_name>
└── <file_name>.go
example
golangdemo
├── main.go
└── utils
└── util.go
util.go
package utils
import (
"math/rand"
"time"
)
func GetRandomNum() int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(100)
}
Initialize a New Module
go mod init <module_name>
generate go.mod
module <module_name>
example
go mod init golangdemo
generate go.mod
module golangdemo
Import Local Packages
import "<module_name>/<package_name>"
example
import "golangdemo/utils"
Call the Exported Function from the Package
<package_name>.Expoered_function()
example
utils.GetRandomNum()
You can access the source code here.