Since the introduction of modules in Go 1.11, the approach to structuring modules and projects has changed. This article explains the new way to reference a module from another directory, particularly in the absence of publishing.
Example:
Suppose you have the following directory structure:
\root\module1 \root\module2
You want to access module2 from module1 using its types and structs.
Unlike the old approach that required placing modules in GOPATH, modules are now created and initialized using the go mod init command:
go mod init github.com/username/modulename
This command generates a go.mod file to track the module's dependencies and a go.sum file to store the dependency hashes.
To access module2 from module1, you need to add module2 as a dependency in module1's go.mod file:
module github.com/username/module1 require github.com/username/module2 v0.0.1
Once the dependency is added, you can import module2 into your code in module1 using the following syntax:
import "github.com/username/module2"
This will allow you to use the types and structs defined in module2 within your code in module1.
The above is the detailed content of How to Properly Structure and Reference Golang Modules Without Publishing?. For more information, please follow other related articles on the PHP Chinese website!