胡說八道
Go 是一個開源的程式設計語言,它能讓構造簡單、可靠且高效的軟體變得容易。
現代計算機技術的發展已經快打破英特爾戈登·摩爾提出的摩爾定律了。計算機硬體的發展速度已經遠遠趕不上軟體技術的發展,意味着在現有硬體基礎上,高效的性能才是王道。像Go、Rust等這樣的語言才是未來的主導語言。
在開發人員眼中,寫出完美的API很容易,可寫好文檔卻不容易,還有各種示例程式。然而Go、Rust等這類的語言本省就帶了快捷編寫文檔的指令。用起來也相當舒服。接下來,通過執行個體來示範一下Go的API文檔編寫。
建立工程
|--src
|----queue
| | queue.go
| | queue_test.go
|------queueentry
| | main.go
queue.go
編寫的重點在每個類型和方法上邊的注釋上,正是有了編寫的這些注釋,才有了文檔中的說明,so, 一定要寫好注釋!
package queue
// 先進先出隊列
type Queue []int
// 向隊列中添加一個元素
// e.g. q.Push(9)
func (q *Queue) Push (v int) {
*q = append(*q, v)
}
// 從隊列中删除第一個元素
func (q *Queue) Pop () int {
head := (*q)[0]
*q = (*q)[1:]
return head
}
// 如果隊列為空,則傳回true
func (q *Queue) IsEmpty () bool {
return len(*q) == 0
}
queue_test.go
go還可以給寫的庫或者包寫示例。我的IDE是GoLand, 你隻要在與queue.go這個檔案同目錄建構一個queue_test.go檔案,在檔案中鍵入 func Ex..之後,編輯器會自動彈出提示,讓你選擇實作哪一個方法的示例的方法名。還是很貼心的。如果要寫出示例程式執行的結果,隻需要在示例程式中用// Output寫出執行結果即可。
package queue
import "fmt"
func ExampleQueue_Pop() {
q := Queue{1}
q.Pop()
// Output
// 1
}
func ExampleQueue_Push() {
q := Queue{1}
q.Push(2)
}
func ExampleQueue_IsEmpty() {
q := Queue{1}
if !q.IsEmpty() {
fmt.Println("empty")
}
// Output
// empty
}
暫停......
最為一個庫, 我們肯定要使用,是以,我們引用queue.go,将其打包為一個可執行檔案,就當自個測試了。
main.go
相信你能看懂。
package queueentry
import (
"fmt"
"queue"
)
func main() {
q := queue.Queue{1}
q.Push(2)
fmt.Println(q[1])
}
線上看文檔
go為我們提供了go doc 指令和 godoc兩個指令檢視文檔,兩個指令的使用方式也是不同的。如下是兩個指令的大緻使用。
go doc
$ go doc fmt.Println
func Println(a ...interface{}) (n int, err error)
Println formats using the default formats for its operands and writes to
standard output. Spaces are always added between operands and a newline is
appended. It returns the number of bytes written and any write error
encountered.
godoc
$ pwd
/gopath/to/src/queue/
$ godoc -http 127.0.0.1:8089
... # 啟動了一個web伺服器,用浏覽器即可打開。
在此,為了友善檢視其它庫的API,我們使用godoc指令格式。
執行後打開浏覽器,會進入go提供的預設的網頁。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL4EDZwQWZxkDZkRjZjV2MmBDO5QDZhNTYzMmMjJGMldDZmdTYhVWMk9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)
點選頂部的Packages,該頁面包含了Go的标準庫,和你剛才寫了注釋的庫。
在頁面搜尋queue,定位到該詞的位置;
點選該文字,進入該庫的說明文檔;
至此,你的API的說明文檔可以用了,可以把你的庫交給你的小夥伴了。
打包
$ pwd
/gopath/to/src/queue/entryqueue/
go build main.go
# 生成entryqueue.exe
添加到bin
$ pwd
/gopath/to/src/queue/entryqueue/
go install
測試
$ entryqueue
2 # 測試成功
亂種取整
Go 為我們提供了一整套的編寫文檔的工具,不像java、JavaScript等語言都需要安全插件并且需要有特定的格式,操作很是麻煩。