Multiple Source Directories for Go Packages
In Go, developing a package with multiple source directories can be challenging, especially when you want to organize your code structure while maintaining ease of import for users.
While it may seem natural to declare the same package name in multiple source files across different directories, this approach is not recommended. According to the Go language specification, implementations may require that all source files for a package reside in the same directory. Attempting to import multiple directories from the same package will result in an error:
error: redefinition of ‘mypackage’
Instead of declaring multiple source directories, Go provides several alternatives:
Rename File Names: Structure your file names to mimic folder hierarchy. Instead of:
foo/foo1.go foo/bar/bar1.go foo/bar/bar2.go
Use:
foo/foo1.go foo/bar-bar1.go foo/bar-bar2.go
To summarize, it is not advisable to develop a Go package across multiple source directories. The recommended approaches include renaming file names, splitting packages, or utilizing internal packages. These alternatives enable you to organize your code effectively while ensuring proper package import and visibility.
The above is the detailed content of How Can I Organize a Go Package Across Multiple Directories Without Import Errors?. For more information, please follow other related articles on the PHP Chinese website!