Go example functions are executable test functions embedded in package documentation that demonstrate how to use a package, function, or type. They are written as normal Go functions with names starting with Example, and they are run by the go test tool, which also verifies that any output they produce matches the expected output shown in a comment. This makes them a powerful way to combine documentation with automated testing.
What Are Example Functions?
In Go, an example function is a special kind of function that serves two purposes: it provides a runnable example for documentation, and it acts as a test. The Go documentation tool godoc and the go test command recognize functions whose names begin with Example and treat them specially. When you run go test, these functions are executed just like regular test functions. If the example has an output comment, the test framework compares the actual output with the comment and fails if they do not match.
Example functions are written in the same _test.go files as unit tests. They are not included in the compiled binary of your package, but they are compiled and run during testing. This means they can use internal functions and unexported types, which makes them ideal for showing how to use a package from the inside.
How to Write a Basic Example
The simplest example function has no parameters and no return value. Its name must start with Example, optionally followed by a suffix that indicates what it demonstrates. For instance, to show how to use a function called Add, you would write:
func ExampleAdd() {
sum := Add(2, 3)
fmt.Println(sum)
// Output: 5
}
The // Output: comment is crucial. It tells the test tool what the expected output is. If the function prints something different, the test fails. If you omit the comment, the example is still run, but no output comparison is performed; it only checks that the code does not panic.
Naming Conventions and Suffixes
The name of an example function determines where it appears in the documentation. The rules are:
Example– demonstrates the package as a whole.ExampleFoo– demonstrates the function or typeFoo.ExampleFoo_Bar– demonstrates the methodBaron typeFoo.ExampleFoo_Bar_baz– demonstrates a specific case of methodBar, often used for multiple examples of the same method.
For example, if you have a type Rectangle with a method Area, you can write ExampleRectangle_Area. If you want to show two different cases, you can append a lowercase suffix like ExampleRectangle_Area_square and ExampleRectangle_Area_rectangle.
Why Use Example Functions?
Example functions offer several benefits beyond simple documentation:
- They are always up-to-date. Because they are compiled and run with the test suite, any change that breaks the example causes a test failure.
- They are interactive. Users can click the “Run” button on the Go playground to execute the example directly in their browser.
- They show real usage. Unlike abstract documentation, examples show actual code that compiles and produces output.
- They serve as regression tests. If a function’s behavior changes, the example’s output comparison will catch it.
For open-source packages, examples are often the first thing a new user looks at. A well-crafted example can be more valuable than a lengthy explanation.
Common Mistakes and Pitfalls
Several mistakes are common when writing example functions:
- Missing the Output comment. If you intend to verify output, you must include
// Output:exactly, with a space after the colon. A typo like//Output:will be ignored. - Incorrect output format. The output comment must match exactly, including spaces and newlines. Trailing spaces or missing newlines cause failures.
- Using an unexported function in the example. If the example is meant to be shown on the package documentation, it should use exported identifiers, otherwise users cannot copy it.
- Forgetting to import
fmt. Most examples usefmt.Println; you need to import it. - Naming conflicts. Two examples with the same name cause a compile error. Use distinct suffixes.
Another subtle issue is that the output comparison ignores the order of lines? No, it does not. It compares the entire output as a string, line by line, in order. If your function prints in a non-deterministic order (e.g., from a map), the example will be flaky.
Example Functions in the Wild
Many popular Go packages use example functions extensively. For instance, the standard library has thousands of them. The sort package demonstrates how to sort a slice with a custom comparator. The json package shows how to marshal and unmarshal structs. These examples are often the quickest way to learn a library.
When browsing documentation on pkg.go.dev, you will see examples listed under the “Examples” section. Each example has a small code block with a run button. Clicking it opens the Go playground with the code pre-loaded, allowing you to experiment without installing anything.
For your own projects, adding examples is a low-cost way to improve documentation and test coverage. The Go toolchain does all the heavy lifting; you only need to write the function and the expected output.
Frequently Asked Questions
Do example functions count as tests?
Yes. They are executed by go test and can fail the build if they produce unexpected output or panic. However, they are not counted in the coverage report by default, because they are not designed to assert behavior beyond output matching.
Can I have multiple examples for the same function?
Yes, you can. Use a lowercase suffix to distinguish them, like ExampleFoo_int and ExampleFoo_string. The suffix can be any lowercase identifier, and it will appear in the documentation as a label.
What happens if I omit the Output comment?
The example is still compiled and run, but no output comparison is performed. It will only fail if the code panics. This is useful for examples that demonstrate a side effect, like writing to a file, where the output is not deterministic.
Can example functions use internal or unexported identifiers?
Yes, because they live in the same package as the code they demonstrate. This is actually a benefit: you can show how to use an unexported helper in a way that users cannot directly copy, but it still serves as a test.
How do I make an example that does not print anything?
Simply write the function without any fmt.Print calls and without an // Output: comment. The test will run the code and check only for panics. This is common for examples that set up a data structure or call a function that returns a value but you do not need to show it.
Are example functions included in the binary?
No. They are only compiled for the test binary. The production build ignores files ending in _test.go, so examples do not affect the size or behavior of your application.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Turn Off Backup Encryption in iTunes?
- Campus Tech Innovation Hubs: What They Are
- Poco C51 Airtel Prepaid Locked Variant India?
- Jenkins vs GitHub Actions: Which CI/CD Fits Your Team?
- Shared VPS Hosting: Is It Better?
- Disk Defrag Pro: What It Does and Whether You Need It