Go 中的可测试示例 - Go 编程语言

  • Introduction: Godoc examples are Go code snippets in package documentation, verified by tests and runnable on the godoc web page. Executable documentation ensures API changes don't make info outdated. The standard library has many examples (like the strings package). This article explains writing own example functions.
  • Examples are tests: Examples are compiled and optionally executed as part of a package's test suite. They are functions in _test.go files, start with Example instead of Test, and take no arguments. For example, the reverse package's ExampleString shows its String function. The Go package documentation server presents examples with function documentation. Running the test suite executes example functions and compares output to comments. Changing the output comment can make an example fail. Removing the output comment compiles but doesn't execute the example. Examples without output comments are useful for non-unit test code.
  • Example function names: Godoc uses a naming convention to associate example functions with package-level identifiers. ExampleFoo documents the Foo function/type, ExampleBar_Qux documents the Qux method of type Bar, and Example documents the package as a whole. Multiple examples can be provided for an identifier using a suffix starting with an underscore and a lowercase letter.
  • Larger examples: Sometimes a function isn't enough for a good example. For the sort package, an implementation of sort.Interface is needed. A "whole file example" is used, which is a file ending in _test.go with exactly one example function, no other test or benchmark functions, and at least one other package-level declaration. Godoc shows the entire file for such examples. A package can have multiple whole file examples (see the sort package's source code).
  • Conclusion: Godoc examples are a great way to document code. They provide editable, working, and runnable examples that users can build on. It is recommended to use them.
阅读 8
0 条评论