- 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
stringspackage). 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.gofiles, start withExampleinstead ofTest, and take no arguments. For example, thereversepackage'sExampleStringshows itsStringfunction. 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.
ExampleFoodocuments theFoofunction/type,ExampleBar_Quxdocuments theQuxmethod of typeBar, andExampledocuments 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
sortpackage, an implementation ofsort.Interfaceis needed. A "whole file example" is used, which is a file ending in_test.gowith 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 thesortpackage'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) `代码` - 列表 > 引用。你还可以使用@来通知其他用户。