Importing Local Packages in Go
Importing local packages is an essential aspect of organizing and modularizing code in Go. However, when moving local packages to a different location, errors may arise. This article addresses two common issues and provides soluzioni for importing local packages in Go.
Error 1: Local Import in Non-Local Package
When encountering the error message "local import "./common" in non-local package," ensure that the import statement is in the correct syntax. Go considers the starting path for imports to be $HOME/go/src. This means that the import statement should include the path to the local package relative to $HOME/go/src.
In this case, the local packages are located at /home/me/go/src/myapp. To resolve the error, update the import statement as follows:
import ( "log" "net/http" "myapp/common" "myapp/routers" )
Error 2: Cannot Find Package
When receiving the error "cannot find package," verify that the Go import path is configured correctly. By default, Go looks for packages in $GOROOT and $GOPATH. The import path should match the relative path of the local package within these directories.
In this instance, the local packages are not located in $GOROOT or $GOPATH. To fix this, configure your Go workspace to include the local package directory by setting the environment variable GOPATH to include /home/me/go/src. You can do this by adding the following line to your shell configuration file (e.g., .bashrc):
export GOPATH=$GOPATH:/home/me/go/src
The above is the detailed content of How Do I Fix Import Errors When Moving Local Go Packages?. For more information, please follow other related articles on the PHP Chinese website!