Home > Article > Backend Development > How Do I Reference Go Modules from Outside the GOPATH?
The introduction of Go modules in Go 1.11 introduced changes in the referencing of modules and packages from non-GOPATH directories.
Old Way
Traditionally, Go modules were required to reside within the GOPATH. Modules and packages within this directory could be imported using the following syntax:
import ( "github.com/username/modulename/subpackage" )
New Way
With Go modules, this approach has changed. Packages can now reside outside of GOPATH. To reference a package from another directory:
Initialize a new module using the go mod init command:
go mod init github.com/username/modulename
This creates go.mod and go.sum files in the current directory.
Use import statements to reference packages from other directories. For example, if Module2 is located at /root/module2, and contains a package named module2, the import statement in Module1 will be:
import ( "github.com/username/module2" )
Assuming the following file structure:
\root └── module1 ├── go.mod └── main.go └── module2 ├── go.mod └── module2.go
Module1:
module github.com/username/module1 require ( github.com/username/module2 v0.0.1 )
Module2:
module github.com/username/module2 go 1.13
package main import ( "fmt" "github.com/username/module2" ) func main() { fmt.Println(module2.Name()) }
package module2 import "fmt" func Name() string { return "Module 2" }
By following these steps, you can reference modules from non-GOPATH directories, enabling the reuse of code and modularity in Go projects.
The above is the detailed content of How Do I Reference Go Modules from Outside the GOPATH?. For more information, please follow other related articles on the PHP Chinese website!