全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-14 5 分钟 ✍️ juanwangdev

Go文档生成

Go从源码注释自动生成文档,无需额外维护文档文件。

go doc命令

查看文档

Bash
# 查看包文档
go doc fmt

# 查看函数文档
go doc fmt.Printf

# 查看方法文档
go doc net/http.Client.Get

# 显示完整文档
go doc -all fmt

# 显示源码
go doc -src fmt.Printf

godoc工具

启动Web服务

Bash
# 启动本地文档服务器
godoc -http=:6060

# 浏览器访问
# http://localhost:6060

# 查看标准库文档
# http://localhost:6060/pkg/

# 查看项目文档
# http://localhost:6060/pkg/github.com/user/project/

命令行查看

Bash
# 查看包文档
godoc fmt

# 查看函数文档
godoc fmt Printf

# 显示源码
godoc -src fmt Printf

文档注释规范

包注释

Go
// Package math provides basic constants and mathematical functions.
//
// For more information, see https://math.org
package math

// 包注释写在package声明上方
// 第一句应该是:Package xxx ...

函数注释

Go
// Add returns the sum of a and b.
// It accepts two integers and returns their sum.
//
// Example:
//
//	result := Add(1, 2) // result = 3
func Add(a, b int) int {
    return a + b
}

// 注释以函数名开头
// 第一句应该是完整句子的总结

类型注释

Go
// User represents a registered user in the system.
type User struct {
    Name string    // User's display name
    Age  int       // User's age in years
}

// 结构体字段注释写在字段后

方法注释

Go
// GetName returns the user's display name.
func (u *User) GetName() string {
    return u.Name
}

// 注释以方法名开头

注释规则

类型格式示例
Package xxx...Package fmt...
函数FuncName...Printf formats...
类型TypeName...User represents...
方法MethodName...GetName returns...
字段行尾注释Name string // 名字

文档示例示例

Go
// Add returns the sum of two integers.
//
// Example:
//
//	sum := Add(1, 2)
//	fmt.Println(sum) // Output: 3
func Add(a, b int) int {
    return a + b
}

// godoc会显示示例代码
// 示例代码可执行(test文件中的Example函数)

Example测试文档

示例函数

Go
// handler_test.go

func ExampleAdd() {
    result := Add(1, 2)
    fmt.Println(result)
    // Output: 3
}

// godoc显示Example
// 且可通过go test验证

示例命名

Go
// Example函数命名规则

ExampleAdd()        // 函数示例
ExampleUser_GetName() // 方法示例
ExampleAdd_second()   // 多个示例

// Output注释验证输出
// Output: 3

注释最佳实践

写好注释

Go
// ✓ 好注释
// GetName returns the user's display name.
func (u *User) GetName() string {
    return u.Name
}

// ✗ 差注释(不解释代码)
// GetName returns u.Name.
func (u *User) GetName() string {
    return u.Name
}

// ✗ 差注释(无意义)
// This function gets the name.
func (u *User) GetName() string {
    return u.Name
}

注释要点

Go
// 1. 以被注释名称开头
// 2. 第一句完整总结
// 3. 解释"是什么",而非"怎么做"
// 4. 提供使用示例
// 5. 更新时同步修改注释

要点总结

  • go doc命令查看包和函数文档
  • godoc -http=:6060启动Web文档服务
  • 包注释:Package xxx...放在package上方
  • 函数注释:以函数名开头,描述功能
  • 类型注释:以类型名开头
  • 方法注释:以方法名开头
  • 字段注释:写在字段同一行后
  • Example函数生成可执行示例
  • 注释解释"是什么",不解释"怎么做"
  • godoc自动从源码生成,无需额外维护

📝 发现内容有误?点击此处直接编辑

← 上一篇 Go反射与代码生成
下一篇 → Go构建与交叉编译
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库