How to Import Local Packages without Gopath in Go

Go Modules feature simplifies package management and allows you to import local packages without GOPATH. You can organize your project and its dependencies more streamlined using Go Modules.

To import local packages using Go Modules, follow the below steps.

Step 1: Initialize a new Go module

To initialize a new Go module, use the following command in your project’s root directory.

go mod init <module-name>

Replace <module-name> with a unique name for your module, such as the project’s repository URL (e.g., github.com/username/myproject). This command creates a go.mod file in your project’s root directory.

Step 2: Create a subdirectory

You can create a subdirectory for your local package inside your project.

mkdir mypackage

Replace mypackage with the desired name for your local package.

Step 3: Create a .go file in the new subdirectory

You can create a .go file in the new subdirectory (e.g., mypackage/mypackage.go) and define your package with its functions or types.

Step 4: Import the local package

To import the local package in another file within the same module, you can use the module name followed by the package name.

import (
  "<module-name>/mypackage"
)

Replace the <module-name> with the name you used when initializing the Go module, and mypackage with the name of your local package.

Here’s a simple example:

Directory structure:

myproject/
│── go.mod
│── main.go
└── mypackage/
 └── mypackage.go

The go.mod file looks like this:

module github.com/username/myproject

go 1.16

The mypackage/mypackage.go file looks like this:

package mypackage

func SayHello() string {
  return "Hello from my local package!"
}

Finally, the main.go file looks like this:

package main

import (
  "fmt"
  "github.com/username/myproject/mypackage"
)

func main() {
  message := mypackage.SayHello()
  fmt.Println(message)
}

In this example, we have a local package called mypackage, which contains a SayHello() function.

In main.go, we imported the local package using the module name (github.com/username/myproject) followed by the package name (mypackage).

We then called the SayHello() function from the imported package and print the returned message.

Make sure to replace github.com/username/myproject with your module name.

That’s it.

Leave a Comment