Golang中何时使用示例?

Golang中何时使用示例? 大家好,

你们通常在什么时候使用示例?你们是否将它们与 godoc 结合使用?如果你们一直在使用它们,能否分享更多细节?

就我个人而言,我正在尝试进行代码文档化,godoc 中出现的一些示例可能很有价值,但我不确定这是否是标准做法。

2 回复

在 godoc 中包含示例是标准做法:

favicon.ico

http 包 - net/http - Go 包

Package http provides HTTP client and server implementations.

另请参阅:

favicon.ico

godoctricks 包 - github.com/fluhus/godoc-tricks - Go 包

Package godoctricks is a tutorial on the features of GoDoc.

接下来,看看这个示例:

favicon.ico

http 包 - net/http - Go 包

Package http provides HTTP client and server implementations.

然后看看对应的代码:

https://cs.opensource.google/go/go/+/master:src/net/http/example_test.go;l=59?q=%2F%2F%20Simple%20static%20webserver:&ss=go%2Fgo:src%2Fnet%2Fhttp%2F

对我来说,示例通常是我开始使用一个模块所需的全部内容,因此它们极其有用。我可以快速获得一个示例,然后通过智能感知/直接探索源代码来发现我正在使用的模块的其他功能。不过我想这取决于具体的模块。

更多关于Golang中何时使用示例?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go项目中,示例(examples)主要用于两个关键场景:文档演示测试验证。它们通过go test运行,并集成在godoc中,是Go语言官方推荐的文档实践。

1. 何时使用示例?

  • 演示包/函数用法:展示如何调用函数、初始化类型或使用接口。
  • 验证代码行为:示例作为可执行测试,确保示例代码与当前版本兼容。
  • 提供模板代码:为用户提供可直接复用的代码片段。

2. 与godoc的结合

示例文件(以_example_test.go结尾)会被godoc自动抓取,并显示在对应包/函数的文档中。例如:

// 文件:strings_example_test.go
package strings_test

import (
    "fmt"
    "strings"
)

func ExampleToUpper() {
    fmt.Println(strings.ToUpper("hello"))
    // Output: HELLO
}

func ExampleBuilder() {
    var b strings.Builder
    b.WriteString("Hello")
    b.WriteString(", ")
    b.WriteString("World!")
    fmt.Println(b.String())
    // Output: Hello, World!
}

运行go test时会执行示例,并验证// Output:注释中的预期输出。godoc将显示这些示例及其输出。

3. 示例类型

  • 包示例:函数名设为Example(),显示在包文档顶部。
  • 函数示例:函数名格式为Example函数名,如ExampleToUpper
  • 类型示例:函数名格式为Example类型名,如ExampleBuilder
  • 方法示例:函数名格式为Example类型名_方法名,如ExampleBuilder_WriteString

4. 完整示例

// 文件:calculator_example_test.go
package calculator_test

import (
    "fmt"
    "github.com/your/calculator"
)

func ExampleAdd() {
    sum := calculator.Add(5, 3)
    fmt.Println(sum)
    // Output: 8
}

func ExampleCalculator_Multiply() {
    calc := calculator.New()
    result := calc.Multiply(4, 7)
    fmt.Println(result)
    // Output: 28
}

这些示例会出现在godoc的Add函数和Calculator.Multiply方法文档中,并通过go test ./...验证。

5. 测试验证

示例代码必须通过编译和运行测试。如果示例输出与注释不匹配,测试将失败:

$ go test -v
=== RUN   ExampleAdd
--- PASS: ExampleAdd (0.00s)
=== RUN   ExampleCalculator_Multiply
--- PASS: ExampleCalculator_Multiply (0.00s)

使用示例是Go的标准实践,它直接提升了文档的可用性和代码的可信度。

回到顶部