和其他语言一样,go语言也提供了详细的查询相关函数/接口/变量等定义和实现的便捷方法:go doc和 godoc就是这样的命令。这篇文章中,通过一些简单的实例来学习一下如何更好的这些随手可以获得的离线帮助信息。
函数确认
比如testing标准包中的Error方法,如何使用在不知道的情况可以如下的方式进行查询确认。
[root@liumiaocn /]# go doc testing.B.Error
func (c *B) Error(args ...interface{})
Error is equivalent to Log followed by Fail.
[root@liumiaocn /]#
变量确认
比如io包中的EOF,可以如下的方式进行查询确认。
[root@liumiaocn /]# go doc io.EOF
var EOF = errors.New("EOF")
EOF is the error returned by Read when no more input is available. Functions
should return EOF only to signal a graceful end of input. If the EOF occurs
unexpectedly in a structured data stream, the appropriate error is either
ErrUnexpectedEOF or some other error giving more detail.
[root@liumiaocn /]#
学习源码
学习一门语言最好的教程应该莫过于其标准库的实现。go语言的也提供非常简单的方式用于确认源码,比如以常用的fmt.Println举例,我们可以通过如下方法来确认到其源码的实现。
确认定义
[root@liumiaocn /]# 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.
[root@liumiaocn /]#
确认源码(fmt.Println)
[root@liumiaocn /]# godoc -src fmt Println
use 'godoc cmd/fmt' for documentation on the fmt command
// 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.
func Println(a ...interface{}) (n int, err error) {
return Fprintln(os.Stdout, a...)
}
[root@liumiaocn /]#
可以看出fmt.Println是直接调用Fprintln实现的。
确认源码(fmt.Fprintln)
[root@liumiaocn /]# godoc -src fmt Fprintln
use 'godoc cmd/fmt' for documentation on the fmt command
// Fprintln formats using the default formats for its operands and writes to w.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrintln(a)
n, err = w.Write(p.buf)
p.free()
return
}
[root@liumiaocn /]#
文档服务器
开启文档服务器
通过一条非常简单的命令godoc -http=:8080,即可通过浏览器来确认相关信息
[root@liumiaocn ~]# godoc -http=:8080
支持搜索查询
如果希望能够支持搜索查询,只需要加入index参数即可:godoc -http=:8080 -index
[root@liumiaocn ~]# godoc -http=:8080 -index