Since the release of Go version 1.4 in December 2014 (Go 1.4 Release Notes), the concept of internal packages was introduced to Go developers. This feature enables them to structure their programs with clearer intentions. Like many features in Go, it utilizes a simple naming convention to provide its functionality.
Why use internal packages?
The core of using internal packages lies in their ability to manage visibility and establish clear boundaries within a Go program. By using internal packages, developers can ensure that certain parts of their codebase are "shielded" from external use, thus maintaining a clean and well-defined interface for users and other parts of the program.
Creating an internal package
To take advantage of this feature, you simply need to place the desired package within a directory named internal
, or within any subdirectory of an internal
directory. The Go toolchain enforces access restrictions based on this convention.
In practice
If you navigate to the standard package crypto, you will see these files and directories for that package.
As you can see, there is an internal
directory just in the middle of the image. According to the rules governing internal packages, this package can only be imported by code that lives within the crypto directory tree. This means that code situated outside repository is prohibited from accessing it.
This mechanism ensures that developers can create segments of their codebase that are for internal use only, without fear of them being accidentally depended upon by external parties. It's a critical feature for maintaining modular, secure, and clean code architectures in larger projects.
Full details of the mechanism are in the design document.
Top comments (0)