這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
文章《How to Write Go Code》為Golang.org官方文檔,地址是https://golang.org/doc/code.html。
以下為學習筆記。
文章主要講述了這幾個方面的內容:
- Go的程式碼群組織結構&環境變數設定
- helloworld樣本程式
- stringutil樣本庫
- 單元測試
- 擴充資料(後續學習)
1、Go的程式碼群組織結構&環境變數設定
Go程式碼群組織遵循如下規則:
- 一般只有一個workspace
- 一個workspace下有多個倉庫,隸屬於不同的版本控制工具
- 每個倉庫有多個package
- 每個package是一個獨立的目錄,包含多個源檔案
- package的目錄決定了import path
環境變數裡需要設定GOPATH
2、helloworld樣本程式
- 如果使用
go install不指定參數,需要在hello.go所在目錄;
- 如果制定參數,在任何目錄都可以,參數必須是
go install -github.com/user/hello;
下同。
3、stringutil樣本庫
go build參數同上;
- 值得注意的是,
go build不產生輸出,如果想要stringutil.a需要執行go install;
$ go build
This won't produce an output file. To do that, you must use go install, which places the package object inside the pkg directory of the workspace.
4、單元測試
單元測試與C++不可同日而語,太太太先進了!
只需要編寫test函數,調用test命令就行。
5、擴充資料(後續學習)【非常重要】
See Effective Go for tips on writing clear, idiomatic Go code.
Take A Tour of Go to learn the language proper.
Visit the documentation page for a set of in-depth articles about the Go language and its libraries and tools.