Importing Local Packages in Go Without GOPATH
In the absence of GOPATH, importing local packages requires a solution that goes beyond the traditional method. Several options are available depending on the Go version employed.
Using Vgo (Go 1.11 and Later)
Vgo is the recommended dependency manager for Go versions 1.11 and above. It utilizes a "module" system that allows for automatic dependency resolution and version management. To use vgo:
export GO111MODULE=on # Enable Go modules go mod init # Initialize the module go mod vendor # Download and install dependencies go build # Build the project
Using Vendor (Go 1.6 to Go 1.10)
Vendor is a manual dependency management technique that involves creating a "vendor" directory within the project. External packages are placed in this directory, and the compiler will prioritize them during compilation.
Using Manual Import (Go Versions Prior to 1.6)
For earlier Go versions, manual import can be achieved by:
Directory Structure
With manual import, the project directory structure should resemble the following:
myproject/ ├── binary1.go ├── binary2.go ├── package1/ │ └── package1.go └── package2.go
Conclusion
The specific method for importing local packages without GOPATH depends on the Go version being used. While direct importation is possible using subfolders, Go modules (vgo) or vendor capabilities provide more advanced dependency management features.
The above is the detailed content of How Can I Import Local Packages in Go Without GOPATH?. For more information, please follow other related articles on the PHP Chinese website!