Home >Backend Development >Golang >Go Package Structure: Do We Need a `package.go` File, How to Import Internal Files, and Can We Access Types Across Files?
When working with Go, adhering to established conventions is crucial. However, understanding these conventions is paramount before their effective implementation. This article tackles a frequently asked question regarding Go's package structure.
Setup: Following the recommended project structure, we have:
$GOPATH/ src/ github.com/ username/ projectname/ main.go numbers/ rational.go real.go complex.go
main.go:
package main import ( "fmt" "./numbers" ) func main() { fmt.Println(numbers.Real{2.0}) }
Questions:
1. package.go File
The assumption that every package directory requires a package.go file is incorrect. In Go, files within a single directory are automatically grouped into a package. Creating a package.go file is unnecessary.
2. Importing Files Within a Package
Go does not support importing files. Package numbers should be imported directly, rather than individual files like rational.go, real.go, and complex.go. In our example, remove the ./ prefix and use import "github.com/username/projectname/numbers".
3. Sharing Types
Types like Real should be defined in a file within the package, such as real.go. As the files belong to the same package, no additional import statement is needed. Accessing the Real type in main.go as fmt.Println(numbers.Real{2.0}) is correct.
The above is the detailed content of Go Package Structure: Do We Need a `package.go` File, How to Import Internal Files, and Can We Access Types Across Files?. For more information, please follow other related articles on the PHP Chinese website!