How to Use Go Modules and Local Packages
In Go 1.11, modules introduce a new approach to organize and manage Go projects. However, integrating local packages within a module can be challenging. Let's explore a solution to overcome this issue.
Defining the Project Structure
Consider the following project structure:
$GOPATH + src + application/ + main/ + main.go + otherFileUnderMainPackage.go + aLocalPackage/ + someCode.go + someCode_test.go + someMoreCode.go + someMoreCode_test.go
Using the Go Build Command
To compile the code in the main package, use the command go build main/*.go. This compiles the package and stores it in the build cache. Identify the build cache location using:
> go env GOCACHE /home/<user>/.cache/go-build
Importing Local Packages with Relative Paths
The correct import path for local packages can be determined using go doc or go list:
> go doc package docs // import "tools/src/hello/docs" > go list tools/src/hello/docs
In your example, the import path for a local package named "aLocalPackage" would be:
import "../aLocalPackage"
By following these guidelines, you can successfully integrate local packages within Go modules, ensuring your project remains well-organized and maintainable.
The above is the detailed content of How to Effectively Use Local Packages within Go Modules?. For more information, please follow other related articles on the PHP Chinese website!