引言
- golang的访问权限有3种 (公有、私有、内部包)
- golang没有和其他语言一样有public、protected、private等访问控制修饰符
- golang通过字母大小写来控制可见性的
- 定义的常量、变量、类型、接口、结构、函数等的名称是大写字母开头才可以被访问或调用
- internal(内部包重点)
相关代码就不多说了有很多案例
内部包
internal 主要是控制只在当前package访问(内部包),一般写开源的框架会有很多地方用到
只有直接父级package可以访问,其他的都不行,再往上的祖先package也不行
父级package也只能访问internal package使用大写暴露出的内容,小写的不行
官方描述
Go’s package system makes it easy to structure programs into components with clean boundaries, but there are only two forms of access: local (unexported) and global (exported). Sometimes one wishes to have components that are not exported, for instance to avoid acquiring clients of interfaces to code that is part of a public repository but not intended for use outside the program to which it belongs.
The Go language does not have the power to enforce this distinction, but as of Go 1.4 the go command introduces a mechanism to define “internal” packages that may not be imported by packages outside the source subtree in which they reside.
To create such a package, place it in a directory named internal or in a subdirectory of a directory named internal. When the go command sees an import of a package with internal in its path, it verifies that the package doing the import is within the tree rooted at the parent of the internal directory. For example, a package …/a/b/c/internal/d/e/f can be imported only by code in the directory tree rooted at …/a/b/c. It cannot be imported by code in …/a/b/g or in any other repository.
For Go 1.4, the internal package mechanism is enforced for the main Go repository; from 1.5 and onward it will be enforced for any repository.