Goのinternalパッケージとは
はじめに
Goのinternalパッケージは、Go1.4で導入されました。
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.
説明によると、goコマンドはinternalをパスにもつimportを見つけると、そのパッケージがinternalディレクトリの親ディレクトリをルートとするツリーにあるかどうかを検証します。
例として、.../a/b/c/internal/d/e/f
は.../a/b/c
ディレクトリをルートとするディレクトリツリーの中からのみインポートできます。そのため、.../a/b/g
や、その他からはインポートできません。
具体例
更に具体例を見ることにします。
つぎのようなパッケージの構成を例に考えてみます。
├── a
│ ├── b
│ │ ├── c
│ ├── internal
├── d
このとき、a/internal
をインポート可能なパッケージは以下のようになります。
-
a
=> インポートできる -
a/b
=> インポートできる -
a/b/c
=> インポートできる -
d
=> インポートできない
パッケージaはa/internal
の親ディレクトリであるため、a/internal
をインポート可能です。
a/b
とa/b/c
はa
ディレクトリをルートとするディレクトリツリーの中にあるため、これもa/internal
をインポートできます。
パッケージd
はこれらの外に存在するパッケージのため、a/internal
をインポートすることはできません。
Discussion