Go, please
1. 背景
折腾 VS Code 写 Go 的朋友都有这种体会,VS Code 的 Go 插件体验上还是输给 GoLand 不少,尤其是代码补全和提示,GOPATH
没配置好或者项目路径在GOPATH
之外就基本残废。
但是我还是坚持用 VS Code,毕竟人家开源,又有微软爸爸背书,相比 GoLand 更加轻量,快捷键用的也更顺手,其实最主要还是没钱 QAQ。
2. gopls
gopls 实现了 VS Code 的 Language Server Protocol (LSP),发音为go please
。
Go Team 目前正在积极维护gopls
,有望成为之后 VS Code Go 插件的默认补全工具,但目前还是有很多小问题,例如下面这个Known issue
:
- Cursor resets to the beginning or end of file on format: #31937.
相似的问题还有下面这个:
- Cursor flies to top of file on save and text flashes: #2728
只在 Windows 环境下出现,因为 Windows 默认的换行符是CRLF
,而目前gopls
的格式化只支持LF
换行。
Windows 可以设置
"files.eol": "\n"
暂时规避一下,评论里提到之后会解决这个问题
目前已知的 Known issues:
- Cursor resets to the beginning or end of file on format: #31937
- Editing multiple modules in one editor window: #32394
- Language features do not work with cgo: #32898
- Does not work with build tags: #29202
- Find references and rename only work in a single package: #32869, #32877
- Completion does not work well after go or defer statements: #29313
- Changes in files outside of the editor are not yet tracked: #31553
期待 Go Team 早日解决🍻
3. VS Code 相关设置
"go.useLanguageServer": true,
"[go]": {
"editor.snippetSuggestions": "none",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},
"gopls": {
"completeUnimported": true,
"usePlaceholders": true,
"completionDocumentation": true,
"hoverKind": "SynopsisDocumentation" // No/Synopsis/Full, default Synopsis
},
"files.eol": "\n", // formatting only supports LF line endings
此外还有一些ExperimentalFeatures
:
"go.languageServerExperimentalFeatures": {
"format": true,
"autoComplete": true,
"rename": true,
"goToDefinition": true,
"hover": true,
"signatureHelp": true,
"goToTypeDefinition": true,
"goToImplementation": true,
"documentSymbols": true,
"workspaceSymbols": true,
"findReferences": true,
"diagnostics": false
},
最后提供一份自用的 VS Code 用户设置,仅供参考:用户设置 - VS Code | Coding-Notes
参考文章
gopls
- gopls documentation - golang/tools | Github
- x/tools/gopls: formatting resets cursor after save with CRLF line endings - golang/go | Github
- Cursor flies to top of file on save and text flashes - microsoft/vscode-go | Github
- gopls - 及时的代码补全 | arbent
- 在 VS Code 中使用 gopls | SegmentFault
- VS Code 中的代码自动补全和自动导入包 | 茶歇驿站
- VSCode 写 Golang,请切换到 Google 官方语言服务器 gopls,有质的提升 | 论坛爱好者