Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

Key Takeaways

  • Example functions in Go are testable code snippets that serve as documentation and can be used to verify correctness.
  • Example functions follow a naming convention and can be defined for packages, functions, types, and methods.
  • Example functions are executable tests and can be used to ensure reliable code and keep documentation up to date.

One of Go’s strengths is its wealth of built-in testing and documentation features. Among these is a highly useful tool called "example functions" that can help you check your code and explain it to others.

As a Go developer, you should understand exactly what example functions are and how you can use them to build maintainable software.

What Are Example Functions?

Example functions (or examples) in Golang are testable snippets of code that you can add to a package as documentation and verify for correctness. Example functions don’t take parameters and don’t return a result either.

Imagine you have the following Multiply function in your project:

 func Multiply(a, b int) int {
    return a * b
}

An example function for Multiply will look like this:

 func ExampleMultiply() {
    fmt.Println(Multiply(4, 5))
    // Output: 2
}

Example functions use a similar naming convention to test functions. Define a function example by adding the function’s name as a suffix to "Example", as is the case with ExampleMultiply here.

Taking a Closer Look at Example Functions

The code in the previous section shows the basic structure of an example function. What makes up an example is the name, function body, and an optional output comment at the end of the function.

When you add the output comment, Go compiles and executes the example to verify its correctness, but without the comment, Go only compiles the example function, it doesn’t execute it.

You can define an example for a package, a function, a type, and a method on a type.

Defining examples for different entities requires different approaches.

  1. To define an example for a package, just call your function Example(), without any suffix. For instance, here’s a package-level example:
     func Example() {
        fmt.Println("Hello, world!")
        // Output:
        // Hello, world!
    }
  2. To define an example for a function, you simply add the function name as a suffix as you learned earlier.
     func ExampleMultiply() {
        fmt.Println(Multiply(4,5))
        // Output: 2
    }
  3. To define an example for a type, add the name as a suffix to Example. Here’s an example:
     type MyStruct struct {
        // ...
    }

    func ExampleMyStruct() {
        // ...
    }
  4. And lastly, for a method on a particular type, you add the type name, an underscore, and then the method name. Here’s a demonstration:
     func (m *MyStruct) MyMethod() {
        // ...
    }

    func ExampleMyStruct_MyMethod() {
        // ...
    }

You can define multiple examples for an entity by adding an extra underscore and a suffix beginning with a lowercase letter. For example, ExampleMultiply_second, ExampleMyStruct_MyMethod_second.

You can also have a larger example to explain complex logic by using a whole file example.

A whole file example is a file that ends in _test.go and contains exactly one example function, no test or benchmark functions, and at least one other package-level declaration. When displaying such examples godoc will show the entire file. - The go dev blog

The Go engine recognizes and handles your example functions according to how you define them.

You can use the Unordered output alternative for output comments. This is particularly useful in scenarios where your function returns a list that isn’t expected in a specific order.

Documenting Your Code With Example Functions

Example functions are useful for both documentation and testing purposes. An example function usually does a better job of explaining behavior than comments do.

Just like Java’s Javadoc, Go’s built-in documentation tool, godoc, helps document code easily. But you’ll want to document some libraries and functions together to give a more complete understanding of how they work. Examples eliminate this setback as they can demonstrate the interactions between various units of a package.

The godoc tool automatically associates examples with the functions, types, and packages they belong to, depending on your specifications. It also goes one step further by allowing experimentation within the documentation web interface.

You can try out a package or method right from the documentation before even using it in your code.

This image shows an example for the json.Valid function under encoding/json:

Screenshot of testable example for the Valid function in golang encoding json package

Using Example Functions to Unit Test

Go example functions are also executable tests. When you run the go test command, the engine runs every example function with a final output comment and ensures its output matches what is in the comment.

This capability is useful in many ways. It can serve as an extra layer of testing to ensure reliable code, it also helps you keep track of your documentation as your code changes.

For instance, if you make a change that impacts how a specific function runs and the result it returns. If you don't update the output comment in the example to meet the new changes, the tests for that example will fail.

This helps a great deal in preventing stale documentation, as your documentation will always be up to date with the code.

Example Functions Produce Reliable Code and Documentation

Documentation is an essential part of software development, but few languages give you such a powerful platform to document and test your code.

Go comes with everything you need to create quality documentation for your software, and example functions are a vital part of that. Use examples to help users and collaborators adopt and understand your code faster.