這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。前面講了測試和效能調優之類,這篇主要講如何利用Go提供的一些工具和參數,協助寫出更好的代碼.
一. golint 檢查代碼規範
二. go vet 檢查代碼存在的隱患
三. -race 檢查是否有race condition
一. golint 檢查代碼規範
/*golint 例子Author: xclDate: 2015-11-22*/package mainimport ("fmt")const fooId = "blah"var var_name inttype hidden struct{}func Exported() hidden {return hidden{}}type T struct{}func main() {Exported()}/*E:\GOtest\testing\testlint>golint -hUsage of golint: golint [flags] # runs on package in current directory golint [flags] package golint [flags] directory golint [flags] files... # must be a single packageFlags: -min_confidence float minimum confidence of a problem to print it (default 0.8)E:\GOtest\testing\testlint>dir 磁碟機 E 中的卷是 doc 卷的序號是 0E3D-2A1F E:\GOtest\testing\testlint 的目錄2015/11/22 21:00 <DIR> .2015/11/22 21:00 <DIR> ..2015/11/22 20:57 6,448,128 golint.exe2015/11/22 21:41 1,066 main.go 2 個檔案 6,449,194 位元組 2 個目錄 15,122,874,368 可用位元組E:\GOtest\testing\testlint>golint main.gomain.go:15:7: const fooId should be fooIDmain.go:17:5: don't use underscores in Go names; var var_name should be varNamemain.go:21:1: exported function Exported should have comment or be unexportedmain.go:21:17: exported func Exported returns unexported type main.hidden, which can be annoying to usemain.go:25:6: exported type T should have comment or be unexportedE:\GOtest\testing\testlint>*/列出了具體到哪一行,可能存在的問題.
二. go vet 檢查代碼存在的隱患
/*go vet 例子go doc cmd/vetAuthor: xclDate: 2015-11-22*/package mainimport ("fmt")func main() {var c stringfmt.Sprintf("xxx s", c)}/*E:\GOtest\testing\testvet>dir 磁碟機 E 中的卷是 doc 卷的序號是 0E3D-2A1F E:\GOtest\testing\testvet 的目錄2015/11/22 21:47 <DIR> .2015/11/22 21:47 <DIR> ..2015/11/22 21:47 98 main.go 1 個檔案 98 位元組 2 個目錄 15,122,874,368 可用位元組E:\GOtest\testing\testvet>go vetmain.go:9: result of fmt.Sprintf call not usedmain.go:9: no formatting directive in Sprintf callexit status 1*/
三. -race 檢查是否有race condition
/*race例子go run -race trace.goAuthor: xclDate: 2015-11-22*/package mainimport ("time")var (g int)func main() {go func() {g++}()go func() {g = g + 2}()time.Sleep(1 * time.Second)}/*E:\GOtest\testing\testvet>go run trace.goE:\GOtest\testing\testvet>go run -race trace.go==================WARNING: DATA RACEWrite by goroutine 6: main.main.func2() E:/GOtest/testing/testvet/trace.go:27 +0x37Previous write by goroutine 5: main.main.func1() E:/GOtest/testing/testvet/trace.go:23 +0x53Goroutine 6 (running) created at: main.main() E:/GOtest/testing/testvet/trace.go:28 +0x57Goroutine 5 (finished) created at: main.main() E:/GOtest/testing/testvet/trace.go:24 +0x3f==================Found 1 data race(s)exit status 66E:\GOtest\testing\testvet>*/
這幾個比較常用,當然還有其它很多的協助工具輔助就不在這一一列舉了.
BLOG: http://blog.csdn.net/xcl168