liveBook · Manning

Example function

As explained in Learn Go with Pocket-Sized Projects

A Go example function is a specially named function that demonstrates code usage and can be executed by Go's test tooling when it declares expected output.

A Go example function demonstrates how to use code and can verify standard output when its name follows the Example<FunctionName> convention and its body declares expected output. section 2.1.2 section 2.6

Use the convention as follows:

  • Place tests for unexposed functions in the same package as the source file. section 2.1.2
  • Name the function with Example<FunctionName>; for an unexposed main function, Example_main follows the demonstrated convention. section 2.1.2
  • Call the tested function, then add an // Output: comment followed by the expected standard-output lines. section 2.1.2
  • Run go test to execute eligible examples; without an Output comment, an example is compiled and documented but not executed during tests. section 2.1.2

Checking printed output

A test function can call main and declare Hello world as the expected output. Running go test reports PASS when the generated output matches. section 2.1.2 section 2.6

Listing 2.2 main_internal_test.go: Testing the printed output
package main

func Example_main() {
    main() #1
    // Output: #2
    // Hello world
}

View the complete Example_main listing, including the call to main and the Output comment. section 2.1.2

> go test
PASS
ok      learngo-pockets/hello    0.008s

View the terminal result showing go test passing for the package. section 2.1.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines naming and Output-comment rules, shows a wrapper and test run, but does not detail broader assertion techniques.
Examples
Uses Example_main to wrap main, check Hello world, and produce a passing go test result.
What it assumes
Uses an existing Go function and same-package test file while teaching the example naming and output-comment convention.
What you can do after
Apply it via Go's test tooling to verify printed output or document usage without enforcing a specific output.
How it connects
Connects standard-output verification with test files, go test, go doc, and documentation-oriented usage examples.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.