How to Import Local Packages in Go

To import local packages in Golang, “specify a relative or absolute path to the package directory”.



In this case, main.go is the main program file, and mainpackage is a local package that contains the mainmodule module.

To import the mainpackage package in main.go, you can use the following import statement:

import "./mainpackage"

In this case, the “./ prefix” suggests that mainpackage is a local package, and the path is relative to the directory where main.go is located.

You can then use functions, types, and variables defined in mainpackage in main.go. For example:

package main

import "./mainpackage"

func main() {

Here, we called the MainFunction function defined in mainpackage from the main.go.

Note that importing local packages this way is not recommended for larger projects, as it can make managing dependencies and version control difficult. Instead, a package management tool like Go Modules or vendor packages in a dedicated folder is generally better for managing your project’s dependencies.

Leave a Comment