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

  1. Cursor resets to the beginning or end of file on format: #31937
  2. Editing multiple modules in one editor window: #32394
  3. Language features do not work with cgo: #32898
  4. Does not work with build tags: #29202
  5. Find references and rename only work in a single package: #32869, #32877
  6. Completion does not work well after go or defer statements: #29313
  7. Changes in files outside of the editor are not yet tracked: #31553

期待 Go Team 早日解决🍻

3. VS Code 相关设置

参见 gopls Settings - golang/tools | Github

"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

  1. gopls documentation - golang/tools | Github
  2. x/tools/gopls: formatting resets cursor after save with CRLF line endings - golang/go | Github
  3. Cursor flies to top of file on save and text flashes - microsoft/vscode-go | Github
  4. gopls - 及时的代码补全 | arbent
  5. 在 VS Code 中使用 gopls | SegmentFault
  6. VS Code 中的代码自动补全和自动导入包 | 茶歇驿站
  7. VSCode 写 Golang,请切换到 Google 官方语言服务器 gopls,有质的提升 | 论坛爱好者

goproxy

  1. goproxy.io
  2. goproxy.cn

Go extension

  1. Go tools that the Go extension depends on - microsoft/vscode-go | Github
  2. Visual Studio Code Go 插件文档翻译 | 掘金

Go mod

  1. go mod 使用 | 掘金
  2. VSCode 配置 Go 环境及 Go mod 使用 | 方缘之道
  3. 开始使用 Go Module - isLishude | 知乎
  4. Go Modules 详解 | 后端进阶
  5. Go Modules 不完全教程 | Golang 成神之路
  6. Go Modules 不完全教程 - Golang Inside | 知乎专栏
  7. Go Module 使用实践及问题解决 | banyu