go/typesのCheckでcannot find packageエラーになる
go/importer.Default() を go/types.Config.Importer にセットして Check メソッドを呼び出したとき、以下のようなエラーが返ってくることがある。
example_test.go:11:2: could not import github.com/lufia/plug (can't find import: "github.com/lufia/plug": cannot find package "github.com/lufia/plug" in any of: /usr/lib/go/src/github.com/lufia/plug (from $GOROOT) /home/lufia/src/github.com/lufia/plug (from $GOPATH))exit status 1このエラーは型検査する対象のソースコードが $GOPATH と異なる場所に置いている場合に発生する。
go/typesでgo moduleを有効にするまでの旅路を読むと go/importer がGoモジュールに対応していないように読めるが、実際はそんなことはなく、Goで静的解析する際のテンプレート(標準版)に書いたように Importer の設定を以下に変更すればよい。
c := types.Config{ Importer: importer.ForCompiler(fset, "source", nil),}importer.Default との違いは compiler 引数の値が gc から source に変わっているだけ。ドキュメントによると
ForCompiler returns an Importer for importing from installed packages for the compilers “gc” and “gccgo”, or for importing directly from the source if the compiler argument is “source”.
とあるが、これだけ読んでもよくわからない。