1. golint工具
golint是Go语言提供的一个官方工具,用于查找除代码格式以外的风格缺陷。
与gofmt不同,golint不会被默认安装,安装golint可使用如下命令:
- go get -u github.com/golang/lint/golint
golint所给出的改进建议不是强制性的。
- go lint main.go
- 忽略这些建议既不会导致编译失败,也不会被强行转换
- 为了与整个Go社区保持良好的一致性和可融入性,最好还是采纳这些建议。
- 至少可将其作为一种学习Go语言风格约定和惯用方式的绝佳途径。
事实上,包括Visual Studio Code在内的很多源代码编辑器插件已经可以自动运行glint。
// golint工具用于查找代码中风格缺陷:golint main.go
package main
import "fmt"
const ExportedString = "An exported constant string"
// golint建议:exported const ExportedString should have comment or be unexported
func main() {
fmt.Println(ExportedString)
greeting_string := "Hello World!"
// don't use underscores in Go names; var greeting_string should be
// greetingString
fmt.Println(greeting_string)
}
2. godco工具
godoc是Go语言提供的一个官方工具,用于根据对Go语言源程序的分析和代码中的注释文本,自动生成说明文档。
与golint类似,godoc也不会被默认安装,安装godoc可使用如下命令:
- go get golang.org/x/tools/cmd/godoc
godoc不需要在代码注释中使用特殊的标记或遵从特殊的约定。
- 要给一段代码添加注释,只需在注释行的开头指出被注释元素的名称
- 注释是以大写字母开头,以"."结束的完整句子
运行如下命令生成关于特定包的说明文档:
- godoc animal > animal.txt // 得到animal包纯文本的说明文档
- godoc -html animal > animal.html // 得到animal包的html说明文档
// godoc会将下述绿色标记的注释,自动转化为说明文档。
// Package animal shows how to use the godoc tool.
package animal
import "errors“
// Animal specifies an animal.
type Animal struct {
Name string // Name holds the name of an animal.
Age int // Age holds the age of an animal.
}
// ErrNotAnAnimal returned if the name field of the Animal struct is Human.
var ErrNotAnAnimal = errors.New("Name is not an animal")
// Hello sends a greeting to the animal.
func (animal Animal) Hello() (string, error) {
if animal.Name == "Human" {
return "", ErrNotAnAnimal
}
return "Hello " + animal.Name + "!", nil
}
3. Makefile文件
Go语言提供的三大工具(如下所示),再加上编译器,单独使用过于繁琐,期望自动化。
- 代码格式修正工具:gofmt
- 风格缺陷检查工具:golint
- 说明文档生成工具:godoc
如果我们使用的vscode,那么这一过程已经被图形化的集成开发环境完成。
如果使用的是UNIX操纵系统,不妨借助于Makefile,将Go语言代码的编译链接、格式修正、缺陷检查,甚至文档生成,全部集中到一个单一命令中完成。
- make
// 借助Makefile实现工作流程自动化
// makefile脚本
all: check-gofmt // 定义缺省目录all,其依赖chaeck-gofmt
// 通过一些命令执行gofmt,来检查当前目录下的go源码中是否存在需要格式修正的文件,如果有则列出源文件清单。
check-gofmt:
@if [ -n "$(shell gofmt -l .)" ]; then \
echo 1>&2 'The following files need to be formatted:'; \
gofmt -l .; \
exit 1; \
fi