🐕

Goのinternalパッケージとは

2023/01/12に公開

はじめに

Goのinternalパッケージは、Go1.4で導入されました。
https://go.dev/doc/go1.4#internalpackages

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/ba/b/caディレクトリをルートとするディレクトリツリーの中にあるため、これもa/internalをインポートできます。
パッケージdはこれらの外に存在するパッケージのため、a/internalをインポートすることはできません。

Discussion