Go Module / Packages Question

Hi all,

I am new to Go and I have a question on packages. I have the following directory structure:

image

I am trying to import two different packages into main.go. Package1 which is in the same mod as main.go, imported successfully. However, the numbers package, which is an external package isn’t imported (when running main.go). My main.go:

package main

import (
	"master_go_programming/application_structure/package1"
	"mypackages/numbers"
)

func main() {

	package1.SayHello()
	numbers.AddConsecutiveNums(5)
}

When I run main.go:
$ go run main.go
main.go:5:2: package mypackages/numbers is not in GOROOT (/usr/lib/go-1.18/src/mypackages/numbers)

Is there a way to get this to work without changing the GOPATH? I prefer using GO111MODULE=on but I can’t seem to get this to work.

I solved it by adding the following int the go.mod file

require “mypackages/numbers” v0.0.0
replace “mypackages/numbers” => “…/…/mypackages/numbers”

That’s the correct solution with go.mod.

Go 1.18+ even provides workspaces (via a go.work file) that help to keep the local replacement out of your repository.

And some additional background:

  • With Go Modules, GOPATH only manages the location of module cache and build artifacts. GOPATH is irrelevant for defining source code locations.
  • The most recent Go versions have GO111MODULE enabled by default. Hence no need to use that env var anymore.
  • Typically, the module path that you set inside go.mod points to a remote repository that go get, go mod download and similar commands can fetch the module from. For purely local development, you can ignore that rule, but if you intend to publish a module, consider using the final (remote) module path right from the start.
2 Likes

That helps! Thanks for the explanation!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.