In my Go project, I want to break out some generic functionality into a Go module, separate from the main project. I'm doing this outside of GOPATH in keeping with go's future. I don't want to publish the module on GitHub or anywhere else.
All my attempts to import this module into the main project result in:
cannot find module for path X
I've run go mod init X in the module's folder. The contents of its go.mod file is:
module X
Building or installing this module seems to do nothing. I've found no sign of it in $GOPATH/pgk/mod.
I've tried a variety of import statements:
import "X"import "../x"(relative path to the module directory)import "../x/X"(path to the directory + module name)
Help!
So you wrote a Go "library" module
Xwhich:Use a
replacedirective along withrequireIn your main module's
go.mod, add the following lines:The path should point to the root directory of
X. It can be absolute or relative.To import package util from module X:
(You don't import modules. You import packages from modules.)
Explanation
Go's module functionality is designed for publicly published modules. Normally, a module's name is both its unique identifier and the path to its public repo. When your go.mod declares a module dependency with the
requiredirective, Go will automatically find and retrieve the specified version of the module at that path.If, for example, your
go.modfile containsrequire github.com/some/dependency v1.2.3, Go will retrieve the module from GitHub at that path. But if it containsrequire X v0.0.0, "X" isn't an actual path and you will get the errorcannot find module for path X.The
replacedirective allows you to specify a replacement path for a given module identifier and version. There are many reasons you'd want to do this, such as to test changes to a module before pushing them to the public repo. But you can also use it to bind a module identifier to local code you don't ever intend to publish.More details in the Go Modules documentation:
Hope this helps.