Home >Backend Development >Golang >How to Correctly Import Local Packages in Go?
Importing Local Packages in Go
When working with localized code in Go, importing local packages can sometimes encounter challenges. Here's a detailed analysis of a common issue and its resolution:
Issue:
In an attempt to localize the import statement for packages located in "/home/me/go/src/myapp," the following changes were made:
import ( "./common" "./routers" )
However, upon running "go install myapp," the following errors occurred:
can't load package: /home/me/go/src/myapp/main.go:7:3: local import "./common" in non-local package
Additionally, using "common" and "routers" without the "./" prefix resulted in:
myapp/main.go:7:3: cannot find package "common" in any of: /usr/local/go/src/common (from $GOROOT) /home/me/go/src/common (from $GOPATH) myapp/main.go:8:2: cannot find package "routers" in any of: /usr/local/go/src/routers (from $GOROOT) /home/me/go/src/routers (from $GOPATH)
Solution:
The issue stems from Go's import path convention. Go's starting directory for imports is "$HOME/go/src". To resolve this, simply add the "myapp" prefix to the package names in the import statement:
import ( "log" "net/http" "myapp/common" "myapp/routers" )
This modification ensures that the import paths are correct and will resolve the errors encountered during compilation.
The above is the detailed content of How to Correctly Import Local Packages in Go?. For more information, please follow other related articles on the PHP Chinese website!