- 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 withExample
instead ofTest
, and take no arguments. For example, thereverse
package'sExampleString
shows itsString
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 theFoo
function/type,ExampleBar_Qux
documents theQux
method of typeBar
, andExample
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 ofsort.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 thesort
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.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。