I have been using VS Code to develop Golang program for few years, and recently the issue “no definition found” bothered me a lot.
At the beginning, the issue only happens in the mixed project where the go.mod
is in the sub-directory under the root path. With this case, I still can use navigation feature to jump the editor among struct definition, function implementation or packages by opening the go.mod
path as the root directory with VS Code. However, it even does not work in this way, which pushes me to solve the problem completely.
My existing setup includes:
- VS Code verison: 1.67.0 (latest)
- golang version: 1.17 linux/amd64
- gopls version: v0.8.3
Surprisingly, other issues popped up during solving this issue. I will walk through them all. You can try them one by one and to see if the navigation feature works again. Remember to restart VS Code after each step and then check the effect.
- Add the below setting into the
.vscode/settings.json
{
"go.useLanguageServer": true,
"gopls": {
"build.expandWorkspaceToModule": true,
},
}
-
Call out the “Command Palette..” (Ctrl+Shift+P) and type
Go: Restart Language Server
-
Add one more gopls setting
1{
2 "go.useLanguageServer": true,
3 "gopls": {
4 "build.expandWorkspaceToModule": true,
5 "experimentalWorkspaceModule": true,
6 },
7}
In my case, after step 3, navigation works on some function implementation in the mixed project where the go.mod
is in the sub-directory. And another problem popped up which is all the import package had the error detected in the workspace. In VS Code, they showed as the red line under the package.
There are mainly two kinds of errors:
`Error loading workspace: err: exit status 1: stderr: go: .... disabled by -mod=readonly: packages.Load error`
...go-build.... Permission Denied
When I saw the Permission Denied
, I realized that some packages under the ~/.cache/go-build
might not under the $USER
’s control. And it turned out that most of the packages are controlled by the root
.
As those packages are under the $HOME
directory, I feel confident to change the directory permission by sudo chown -R $USER:$USER ~/.cache/go-build/*
.
After restarting the VS Code, I can see all the detected problems are gone and the navigation worked perfectly as same as before.
If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!