title: go 注釋講解
author: "edte"
tags: ["go"]
date: 2020-06-01
引言
注釋的重要性不言而寓,而怎么編寫注釋也是需要我們學習的,最好的學習教程就是源碼,這篇文章將大量參考 go 庫文件源碼。
分類
go 的注釋有行注釋 //
和塊注釋 /* */
之分。在實際的使用中,行注釋使用得比較多,塊注釋主要用於格式化大段代碼或包的注釋中使用。
在 goland 中行注釋的快捷鍵為 Ctrl+/
, 塊注釋的快捷鍵為 Ctrl+Shift+/
應用
文件注釋
在每個文件中前都加上一段注釋,這段注釋用來描述 作者,時間,以及版權。
我們可以隨便打開一個包查看,如 builtin.go 包中
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
就有時間 2011,作者 go,和版權,我們可以隨便打開其他文件,可以發現只有時間在變,而其他都沒有變化。
在 goland 中可以在 Settings/Editor/File and Code Templates/Files/Go File
中尋改文件注釋模板,這樣每次新建文件都會自動生成注釋。
這是我的模板
//@program: ${PROJECT_NAME}
//@author: edte
//@create: ${YEAR}-${MONTH}-${DAY} ${HOUR}:${MINUTE}
package ${GO_PACKAGE_NAME}
包注釋
包注釋用來描述介紹這個包,以及提供包的一些信息。
在 go 中,一個 目錄中只有一個包(不包擴子目錄),所以一個包中可以有多個文件,一般在其中一個文件寫上包注釋即可。
同樣的,我們來看 builtin 這個包 中的 builtin.go 文件
/*
Package builtin provides documentation for Go's predeclared identifiers.
The items documented here are not actually in package builtin
but their descriptions here allow godoc to present documentation
for the language's special identifiers.
*/
可以看到 builtin 包的作用是給預定義標識符提供文檔。
我們同樣來看 errors 包中的 errors.go 文件,可以看到包注釋很長
// Package errors implements functions to manipulate errors.
這里講了包 errors 實現了一些處理錯誤的功能。
// The New function creates errors whose only content is a text message.
//
// The Unwrap, Is and As functions work on errors that may wrap other errors.
后面還有一大堆,講了 errors 包相關的文件,原理,應用等信息。
如果我們繼續查看源碼,會發現包注釋都是以 package + 一個動詞
開頭的,一般這個短句就說明了這個包的功能,然后再視具體的包說明包的其他信息。
函數注釋
函數注釋用來描述函數的功能,以及其他相關的信息。
我們同樣來看 errros 包中的 errors.go 文件
// New returns an error that formats as the given text.
// Each call to New returns a distinct error value even if the text is identical.
func New(text string) error {
return &errorString{text}
}
這里用一句話說明了 New 功能的作用,即返回一個自定義的錯誤。
然后又用一句話說了這個函數相關的特點,即使文本相同,每次對New的調用也會返回一個不同的錯誤值。
如果同樣查看其他源碼中的函數,我們發現一般幾乎都是 函數名 + 一個動詞
的句子開頭。這個句子同樣說明了這個函數的作用,即函數干了些什么。
而其他需要講解的信息則以復雜度為基礎,如果感覺某個點不容易理解,那么最好都要寫注釋,如函數簽名,函數原理,函數使用過程中需要注意的點等。
數據類型注釋
數據類型注釋說明 這個數據類型用來干什么。
如 errors.go 中
// errorString is a trivial implementation of error.
type errorString struct {
s string
}
這里就說明了 errorString 的作用,即 error 的具體實現。
如 built.go 中
// bool is the set of boolean values, true and false.
type bool bool
// true and false are the two untyped boolean values.
const (
true = 0 == 0 // Untyped bool.
false = 0 != 0 // Untyped bool.
)
// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
type error interface {
Error() string
}
幾乎都是以 類型名 + is
開頭的句子,這個句子說明了這個類型的作用。
TODO
TODO 即 to do, 是一個特殊的注釋,表明在此處有功能等待編寫,
FIXME
FIXME 即 fix me, 也是一個特殊的注釋,表明此處的功能需要修正,甚至不能運行
XXX
XXX 也是一個特殊的注釋,表明此處的功能實現方法有點問題,需要更改
godoc
godoc 是一個實用的工具,可以根據特定的注釋格式生成文檔。也可以用來查看文檔,同樣的 go doc 命令也是相似的作用,具體的可以查看這篇文章。