我正在寻找一种便捷的方法来快速查找 Go 中不同函数和/或包的文档。我目前的方法是通过谷歌搜索
ioutil.ReadFile
,但这非常慢/不方便。
理想的解决方案将直接在 vim 中工作,或者可能在 Go 解释器中工作(建议?)。
例如在 Python 中,可以通过将鼠标悬停在函数上或使用 ipython 解释器在 PyDev 中显示函数的文档,例如
os.open?
或 help(os.open)
。
如何查看 Go 的具体文档?
你有很多可能性:
$ godoc io/ioutil ReadFile
PACKAGE DOCUMENTATION
package ioutil
import "io/ioutil"
FUNCTIONS
func ReadFile(filename string) ([]byte, error)
ReadFile reads the file named by filename and returns the contents. A
successful call returns err == nil, not err == EOF. Because ReadFile
reads the whole file, it does not treat an EOF from Read as an error to
be reported.
$
doc
[0]。$ doc ioutil.ReadFile
http://golang.org/pkg/io/ioutil/#ReadFile
/home/jnml/go/src/pkg/io/ioutil/ioutil.go:48:
// ReadFile reads the file named by filename and returns the contents.
// A successful call returns err == nil, not err == EOF. Because ReadFile
// reads the whole file, it does not treat an EOF from Read as an error
// to be reported.
func ReadFile(filename string) ([]byte, error)
$
[0]:
$ go get code.google.com/p/rspace.cmd/doc
在 Vim 中(假设您已经安装了 Go 的插件),输入
:Godoc <something>
,您将在不离开编辑器的情况下获得文档。显然,您可以将一个键映射到此(没有参数,如果我没记错的话,它会在光标位置搜索令牌)。
话虽这么说,我也经常在 Vim 中使用 Rob Pike 的
doc
来代替 (:!doc <something>
)。
您可以使用 godoc 命令行工具来实现此目的。
godoc os Open
将查找 os.Open
并仅显示与该功能相关的内容。您可以使用 -ex
打开示例。
示例:
$ godoc os Signal
PACKAGE DOCUMENTATION
package os
import "os"
TYPES
type File struct {
// contains filtered or unexported fields
}
File represents an open file descriptor.
func Open(name string) (file *File, err error)
Open opens the named file for reading. If successful, methods on the
returned file can be used for reading; the associated file descriptor
has mode O_RDONLY. If there is an error, it will be of type *PathError.
您还可以运行
godoc -http
,它将运行一个网络服务器,向您显示所有包的文档(默认端口 6060)。
查看 godoc 文档。这是一个很棒的工具,它可以做更多事情。
还有 godoc.org,它基本上是一个替代的
godoc
Web 前端,如果提供了这样的 go 路径,它会自动为托管在其他地方的第 3 方 go 代码生成文档 http://godoc.org/github .com/golang/groupcache#Context.
您可以在终端中运行以下命令。 (使用的Go版本是1.22)
go doc -src <packageName>.<methodname>
例如要查看io包的
ReadAll
的文档,只需输入
go doc -src io.ReadAll