gopl-zh.github.com/ch10/ch10-07-4.md

75 lines
3.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 10.7.4. 包文檔
Go語言的編碼風格鼓勵爲每個包提供良好的文檔。包中每個導出的成員和包聲明前都應該包含目的和用法説明的註釋。
Go語言中包文檔註釋一般是完整的句子第一行是包的摘要説明註釋後僅跟着包聲明語句。註釋中函數的參數或其它的標識符併不需要額外的引號或其它標記註明。例如下面是fmt.Fprintf的文檔註釋。
```Go
// Fprintf formats according to a format specifier and writes to w.
// It returns the number of bytes written and any write error encountered.
func Fprintf(w io.Writer, format string, a ...interface{}) (int, error)
```
Fprintf函數格式化的細節在fmt包文檔中描述。如果註釋後僅跟着包聲明語句那註釋對應整個包的文檔。包文檔對應的註釋隻能有一個譯註其實可以有多個它們會組合成一個包文檔註釋包註釋可以出現在任何一個源文件中。如果包的註釋內容比較長一般會放到一個獨立的源文件中fmt包註釋就有300行之多。這個專門用於保存包文檔的源文件通常叫doc.go。
好的文檔併不需要面面俱到文檔本身應該是簡潔但可不忽略的。事實上Go語言的風格更喜歡簡潔的文檔併且文檔也是需要像代碼一樣維護的。對於一組聲明語句可以用一個精鍊的句子描述如果是顯而易見的功能則併不需要註釋。
在本書中,隻要空間允許,我們之前很多包聲明都包含了註釋文檔,但你可以從標準庫中發現很多更好的例子。有兩個工具可以幫到你。
首先是`go doc`命令,該命令打印包的聲明和每個成員的文檔註釋,下面是整個包的文檔:
```
$ go doc time
package time // import "time"
Package time provides functionality for measuring and displaying time.
const Nanosecond Duration = 1 ...
func After(d Duration) <-chan Time
func Sleep(d Duration)
func Since(t Time) Duration
func Now() Time
type Duration int64
type Time struct { ... }
...many more...
```
或者是某個具體包成員的註釋文檔:
```
$ go doc time.Since
func Since(t Time) Duration
Since returns the time elapsed since t.
It is shorthand for time.Now().Sub(t).
```
或者是某個具體包的一個方法的註釋文檔:
```
$ go doc time.Duration.Seconds
func (d Duration) Seconds() float64
Seconds returns the duration as a floating-point number of seconds.
```
該命令併不需要輸入完整的包導入路徑或正確的大小寫。下面的命令將打印encoding/json包的`(*json.Decoder).Decode`方法的文檔:
```
$ go doc json.decode
func (dec *Decoder) Decode(v interface{}) error
Decode reads the next JSON-encoded value from its input and stores
it in the value pointed to by v.
```
第二個工具名字也叫godoc它提供可以相互交叉引用的HTML頁面但是包含和`go doc`命令相同以及更多的信息。10.1節演示了time包的文檔11.6節將看到godoc演示可以交互的示例程序。godoc的在線服務 https://godoc.org ,包含了成韆上萬的開源包的檢索工具。
你也可以在自己的工作區目録運行godoc服務。運行下面的命令然後在瀏覽器査看 http://localhost:8000/pkg 頁面:
```
$ godoc -http :8000
```
其中`-analysis=type`和`-analysis=pointer`命令行標誌參數用於打開文檔和代碼中關於靜態分析的結果。