Relative Imports in Go
In Go, the convention for importing packages from a parent directory is to use absolute paths. Unlike some other languages, Go does not support relative import paths.
Best Practice: Absolute Import Paths
The recommended approach is to organize your code using absolute import paths for all packages, even those within the same project. This ensures clarity and avoid ambiguity.
Example
Consider the following project structure, where meme is an import path at $GOPATH/src/matt/meme:
- $GOPATH - src - matt - meme - main.go
To import the meme package from another directory within the project, use the following syntax:
import "matt/meme"
Avoid: Relative Import Paths
While it may seem convenient to use relative import paths, such as import "../../../meme", this approach is discouraged in Go. It can lead to ambiguity and may not work as intended.
Conclusion
For best practices in code organization and import paths, use absolute paths and avoid relative imports in Go.
The above is the detailed content of Why Doesn't Go Support Relative Imports, and What's the Best Practice for Importing Packages?. For more information, please follow other related articles on the PHP Chinese website!