VSCode中如何实现Golang代码自动补全包围符号
VSCode中如何实现Golang代码自动补全包围符号 你好。
在将Go从1.13.8更新到1.20后,VSCode中针对Go的“自动环绕”设置失效了。VSCode中的Go扩展已安装,gopls和其他工具也已安装。该设置设为“languageDefined”——在CSS、HTML和Javascript中它正常工作,但在Go中不行。这是我第二天“绞尽脑汁”试图找出问题所在(在1.13.8版本中一切正常)。如果有人知道是怎么回事——请帮帮我。谢谢。
go version
go version go1.20 linux/amd64 (mint 20.3)
VSCode
Version: 1.75.1
更多关于VSCode中如何实现Golang代码自动补全包围符号的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于VSCode中如何实现Golang代码自动补全包围符号的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在VSCode中实现Golang代码自动补全包围符号,需要正确配置gopls和相关设置。以下是解决方案:
1. 更新gopls到最新版本
go install golang.org/x/tools/gopls@latest
2. 检查VSCode Go扩展设置
在VSCode设置中搜索以下配置:
{
"editor.autoClosingBrackets": "languageDefined",
"editor.autoClosingQuotes": "languageDefined",
"editor.autoSurround": "languageDefined",
"[go]": {
"editor.autoClosingBrackets": "always",
"editor.autoClosingQuotes": "always",
"editor.autoSurround": "languageDefined"
}
}
3. 配置gopls设置
在VSCode的settings.json中添加:
{
"gopls": {
"ui.semanticTokens": true,
"ui.completion.usePlaceholders": true,
"ui.completion.autoimport": true,
"ui.completion.bracketMatching": true,
"hints": {
"assignVariableTypes": true,
"compositeLiteralFields": true,
"compositeLiteralTypes": true,
"constantValues": true,
"functionTypeParameters": true,
"parameterNames": true,
"rangeVariableTypes": true
}
}
}
4. 检查语言服务器配置
确保使用gopls作为语言服务器:
{
"go.useLanguageServer": true,
"go.languageServerFlags": [
"-remote=auto",
"-debug=:0"
],
"go.languageServerExperimentalFeatures": {
"autoComplete": true,
"diagnostics": true,
"documentLink": true,
"format": true,
"rename": true,
"symbol": true
}
}
5. 重启VSCode和语言服务器
- 按
Ctrl+Shift+P打开命令面板 - 输入并选择
Go: Restart Language Server - 或者完全重启VSCode
6. 验证自动补全功能
创建测试文件验证功能是否正常:
package main
func main() {
// 测试自动补全包围符号
// 输入 str := "hello" 应该自动补全引号
// 输入 arr := []int{1, 2, 3} 应该自动补全花括号
str := "hello world"
arr := []int{1, 2, 3}
m := map[string]int{"key": 1}
// 测试结构体字面量
type Person struct {
Name string
Age int
}
p := Person{Name: "John", Age: 30}
// 测试函数调用
fmt.Println(str)
}
7. 如果问题仍然存在,尝试重置配置
# 清除gopls缓存
rm -rf ~/.cache/gopls
# 重新初始化Go模块
go mod tidy
8. 检查Go扩展版本
确保安装的是官方的Go扩展:
- 扩展ID:
golang.go - 发布者: Go Team at Google
在VSCode中按Ctrl+Shift+X,搜索Go扩展,确认版本是最新的。
这个配置应该能解决Go 1.20版本下的自动环绕符号问题。如果仍然有问题,可能是特定环境配置导致的,可以检查VSCode的开发者控制台查看相关错误信息。

