解决vscode编写go代码时提示过慢(gopls)
之前用的vscode的自动代码提示,发现太慢了,隔3,4秒才会出提示,所以换为Google推荐的 gopls来代替。
方案一
打开 VS Code 的setting, 搜索 go.useLanguageServe, 并勾选上.
默认情况下, 会提示叫你reload,重新打开之后,右下角会自动弹出下载的框框,点击 install即可。
如果下载时间过长,不成功,可以看方案二
方案二
直接上 github 下载,下载下来 之后go install github.com/golang/tools/cmd/gopls
安装
方案三
go get golang.org/x/tools/gopls@latest
,不需要加u
可以去github上看看文档是怎么说的
配置过程
在github文档里有提示 Use the VSCode-Go plugin, with the following configuration:
"go.useLanguageServer": true,
"[go]": {
"editor.snippetSuggestions": "none",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true,
}
},
"gopls": {
"usePlaceholders": true, // add parameter placeholders when completing a function
// Experimental settings
"completeUnimported": true, // autocomplete unimported packages
"watchFileChanges": true, // watch file changes outside of the editor
"deepCompletion": true, // enable deep completion
},
"files.eol": "\n", // formatting only supports LF line endings
所以现在需要配置一下 setting.json
配置文件。
在 VSCode中按下Ctrl + Shift + P
,在搜索框中输入settings
,找到Open Settings:JSON
添加上面那段代码即可~
package xx/xx is not in GOROOT (C:\Go\src\xx)
“go run”命令在“.go”文件所在的目录执行就可以,
go run main.go
问题分析
1.目录中有自己的定义包怎么办,出现以下问题,说你的包不在goroot中,就是i说找不到
main.go:4:2: package xx/xx is not in GOROOT (C:\Go\src\xx)
main.go:5:2: package xx/xx is not in GOROOT (C:\Go\src\xx)
问题解决:
该问题就是构建mod的路径不对,以我当前的这个项目为例
common文件夹里面是项目启动main,如果在这里构建mod,然后,这个启动项里面引用了其他几个包(上一级的core,lib,loader等),这时候,就会找不到这些包
解决办法:
在项目根目录下面构建mod包,这些引用的包都在该目录下,这样就没有问题了。以我这里为例,根目录是stbweb,启动项common中引用了其他包,我就直接在stbwb目录下执行go mod init stbweb
即可。然后再进入启动main函数目录去执行go build
,自然就好了
go mod命令
download:download modules to local cache (下载依赖的module到本地cache))
edit :edit go.mod from tools or scripts (编辑go.mod文件)
graph : print module requirement graph (打印模块依赖图))
init :initialize new module in current directory (再当前文件夹下初始化一个新的module, 创建go.mod文件))
tidy : add missing and remove unused modules (增加丢失的module,去掉未用的module)
vendor :make vendored copy of dependencies (将依赖复制到vendor下)
verify : verify dependencies have expected content (校验依赖)
why : explain why packages or modules are needed (解释为什么需要依赖)
写入使用包(go build)
写入使用包,直接执行构建语句,就是go build,然会进行下载对应的包
go build :然会进行下载对应的包,执行完毕后就会文件会出现你使用的一些包,还会出现一个go.sum的文件,记录了你的版本过程
本地保存使用包,命令
go mod vendor
执行该命令后,会出现一个vendor文件夹,里面就是你引用的所有包,由此就可以看出,使用mod后,已经不用依赖于原始的gopath,灵活性更高了。
如果使用过程中有包的变动等,可以使用其他命令辅助,比如go mod tidy
,整理你的包目录。