liveBook · Manning

Example syntax

As explained in Learn Go with Pocket-Sized Projects

Example syntax is Go's convention for defining executable documentation examples and associating them with optional expected output.

Example syntax defines executable documentation examples in Go. A test-file function named with the Example convention can call code and, when paired with an Output comment, verify its standard output. section 2.1.2

Use the convention in three steps:

  • Name the function with the Example pattern; for an unexported main function, Example_main follows the demonstrated convention. section 2.1.2
  • Call the function under test, then place an Output comment containing the expected output. section 2.1.2
  • Run go test to execute examples with expected output; examples without Output still compile and appear in generated documentation. section 2.1.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains naming, output comments, execution, and documentation behavior, but does not detail the testing implementation.
Examples
Uses Example_main to test Hello world output and demonstrates its execution with go test.
What it assumes
Assumes familiarity with Go functions, test files, standard output, and running Go commands.
What you can do after
Apply it via Go testing conventions to create executable examples that verify deterministic standard output.
How it connects
Connects Go testing with standard output, test functions, and generated documentation.

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.