2 min read

如何通过VSCode-Go插件提高开发效率

vscode插件 Go 开发效率

ms-vscode.go 是微软为vscode提供的一款插件

0 安装

  1. 安装 golang:https://golang.org/
  2. 安装 vscode:https://code.visualstudio.com/
  3. 安装 ms-vscode.go:使用 Ctrl+Shift+X 打开 Extensions,搜索安装 Go

Tips: 安装前请设置GOPATH

由于Go插件更多依赖了第三方工具,还需要进行手动安装:

  1. 使用Ctrl+Shift+P打开命令面板
  2. 输入>Go:Install/Update Tools 安装和更新工具
go.toolsGopath setting is not set. Using GOPATH /home/ben/go
Installing 18 tools at /home/ben/go/bin in module mode.
  gocode
  gopkgs
  go-outline
  go-symbols
  guru
  gorename
  gotests
  gomodifytags
  impl
  fillstruct
  goplay
  godoctor
  dlv
  gocode-gomod
  godef
  goimports
  golint
  gopls

Installing github.com/mdempsky/gocode SUCCEEDED
Installing github.com/uudashr/gopkgs/v2/cmd/gopkgs SUCCEEDED
Installing github.com/ramya-rao-a/go-outline SUCCEEDED
Installing github.com/acroca/go-symbols SUCCEEDED
Installing golang.org/x/tools/cmd/guru SUCCEEDED
Installing golang.org/x/tools/cmd/gorename SUCCEEDED
Installing github.com/cweill/gotests/... SUCCEEDED
Installing github.com/fatih/gomodifytags SUCCEEDED
Installing github.com/josharian/impl SUCCEEDED
Installing github.com/davidrjenni/reftools/cmd/fillstruct SUCCEEDED
Installing github.com/haya14busa/goplay/cmd/goplay SUCCEEDED
Installing github.com/godoctor/godoctor SUCCEEDED
Installing github.com/go-delve/delve/cmd/dlv SUCCEEDED
Installing github.com/stamblerre/gocode SUCCEEDED
Installing github.com/rogpeppe/godef SUCCEEDED
Installing golang.org/x/tools/cmd/goimports SUCCEEDED
Installing golang.org/x/lint/golint SUCCEEDED
Installing golang.org/x/tools/gopls SUCCEEDED

Reload VS Code window to use the Go language server
All tools successfully installed. You are ready to Go :).

大功告成!接下来看看如何提高生产力~

1 自动生成测试用例

使用方法:

>Go Generate Unit Tests For Function
>Go Generate Unit Tests For Package
>Go Generate Unit Tests For File

运行时注意是否需要加上 -v 选项

2 自动生成结构实例化

使用方法:

>Go Fill Struct

3 自动实现接口

使用方法:

  1. 编写一个自定义接口
  2. 编写一个需要满足接口的结构体类型
  3. 自动实现接口
>Go Generate Interface Stubs

4 自动增加/删除 tag

使用方法:

>Go Add Tags To Struct Fields

需要修改默认配置请前往 settings.json

5 查找接口的具体实现

使用方法:右键跳转

6 一些重构常用的操作

  • 字段重命名:右键 -> Rename Symbol
  • 字段提取:选中 -> >Go Extract to variable
  • 添加第三方包到工作区:选中 -> >Go Add Package to Workspace

7 保存操作

  • go test:测试
  • go format:格式化
  • go vet:可运行检测
  • go lint:严格模式