Golang: Import Local Packages

Claire Lee
Feb 24, 2023

import “<module_name>/<package_name>

golang import local packages

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.

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Claire Lee
Claire Lee

Responses (1)

Write a response

WOW! Thank you bro. You really helped me dude. Really appreciate it!