gofmt 保存的时候自动 格式化go代码
goimports 保存的时候自动导入处理包,以及自动格式化 用来替代 gofmt
goimports需要先goget 才可以使用
go get golang.org/x/tools/cmd/goimports
如果机器不能翻墙会提示错误:
package golang.org/x/tools/cmd/goimports: unrecognized import path "golang.org/x/tools/cmd/goimports" (https fetch: Get https://golang.org/x/tools/cmd/goimports?go-get=1: dial tcp 216.239.37.1:443: i/o timeout)
从GitHub上获取:
go get -v github.com/gpmgo/gopm
gopm 安装完之后再安装 goimports:
gopm get -g -v golang.org/x/tools/cmd/goimports
如果下载成功会提示
[GOPM] 12-03 16:12:10 [ INFO] App Version: 0.8.8.0307 Beta
[GOPM] 12-03 16:12:10 [ INFO] Local repository path: /Users/wuzhiyuan/.gopm/repos
[GOPM] 12-03 16:12:10 [ INFO] Indicated GOPATH: /Users/wuzhiyuan/go
[GOPM] 12-03 16:12:10 [ INFO] Downloading package: golang.org/x/tools/cmd/goimports@branch:<UTD>
[GOPM] 12-03 16:15:35 [DEBUG] Linking golang.org/x/tools...
[GOPM] 12-03 16:15:35 [ INFO] Got golang.org/x/tools/cmd/goimports@branch:<UTD>
[GOPM] 12-03 16:15:35 [ INFO] Package copied to GOPATH: golang.org/x/tools
[GOPM] 12-03 16:15:35 [ INFO] 1 package(s) downloaded, 0 failed
下载了 goimports 再安装
go install golang.org/x/tools/cmd/goimports
安装成功之后再 GOPATH的bin目录下就会出现 goimports , 记得把 GOPATH加入到 机器的PATH目录
-rwxr-xr-x 1 root root 7696429 Mar 17 18:13 goimports
-rwxr-xr-x 1 root root 9924159 Mar 17 18:06 gopm
修改 ~/.vimrc 文件,增加一行 (我这里是装了vim-go插件的)
" 自动加载包
let g:go_fmt_command = "goimports"
这样保存文件的时候就会自动公式化和导入包源代码
package main
import (
"fmt"
)
func main() {
fmt.Println(1)
fmt.Println(2)
fmt.Println(3)
fmt.Println(4)
fmt.Println(5)
fmt.Println(5)
fmt.Println(strings.ToUpper("gopher"))
}
保存之后
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(1)
fmt.Println(2)
fmt.Println(3)
fmt.Println(4)
fmt.Println(5)
fmt.Println(5)
fmt.Println(strings.ToUpper("gopher"))
}
网友评论