Home >Backend Development >Golang >How Should I Structure Packages and Imports in My Go Project?
Go's package structure plays a crucial role in organizing and managing code effectively. To delve into the principles and conventions surrounding package structure, let's examine a hypothetical project setup within your $GOPATH.
Consider the following project directory:
$GOPATH/ src/ github.com/ username/ projectname/ main.go numbers/ rational.go real.go complex.go
1. The 'package.go' File - A Misnomer
Contrary to misconceptions, you don't need a file named package.go within each package folder. Go automatically determines a package's directory as its package. For example, the files in the numbers folder all belong to the numbers package.
2. Importing Subpackages - The Correct Approach
To import the rational.go, real.go, and complex.go files into numbers.go, you should not use relative imports. Instead, import the entire numbers package using the syntax:
import "github.com/username/projectname/numbers"
3. Package Hierarchy and Type Declarations
Within a package, you can define types and functions. In this case, you can declare a Real type within the real.go file, as shown below:
package numbers type Real struct { Number float64 }
By following these conventions, you can organize your Go code effectively and enhance its readability and maintainability. Remember, the key is to import packages, not individual files, and to avoid creating unnecessary package.go files.
The above is the detailed content of How Should I Structure Packages and Imports in My Go Project?. For more information, please follow other related articles on the PHP Chinese website!