問題
VSCodeで開いるプロジェクトディレクトリ下に複数のgo.mod
が存在すると、BrokenImport
のメッセージが出てしまいます。
解決法
各go.mod
が存在するディレクトリがそれぞれworkspaceであることを明示するために go.work
を作成します。
例えば./gin/go.mod
./http/go.mod
があるとしたら以下を実行します。
$ go work init ./gin ./http
そうすると以下のファイルがプロジェクトディレクトリ直下に作成されます
go.work
go 1.18
use (
./gin
./http
)
go.mod
が多い場合は、go work init
を実行してできた空のgo.work
にエディタのサジェストに頼りながら手入力するのも速いかもしれません。
参考
(検索用)warningの中身
could not import github.com/gin-gonic/gin (cannot find package "github.com/gin-gonic/gin" in any of
/usr/local/go/src/github.com/gin-gonic/gin (from $GOROOT)
/Users/xxxx/go/src/github.com/gin-gonic/gin (from $GOPATH))compilerBrokenImport
以前は以下のメッセージが出ており、vscode側の設定experimentalWorkspaceModule
でも解決できましたが、この設定は今年5月にdeprecatedとなったみたいです。https://github.com/golang/go/issues/52897
gopls requires a module at the root of your workspace.
You can work with multiple modules by opening each one as a workspace folder.
Improvements to this workflow will be coming soon, and you can learn more here:
https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.