Example
Functions
The third kind of function treated specially by go test
is an
example function, one whose name starts with Example
. It has
neither parameters nor results. Here’s an example function for
IsPalindrome
:
func ExampleIsPalindrome() { fmt.Println(IsPalindrome("A man, a plan, a canal: Panama")) fmt.Println(IsPalindrome("palindrome")) // Output: // true // false }
Example functions serve three purposes. The primary one is documentation: a good example can be a more succinct or intuitive way to convey the behavior of a library function than its prose description, especially when used as a reminder or quick reference. An example can also demonstrate the interaction between several types and functions belonging to one API, whereas prose documentation must always be attached to one place, like a type or function declaration or the package as a whole. And unlike examples within comments, example functions are real Go code, subject to compile-time checking, so they don’t become stale as the code evolves.
Based on the suffix of the Example
function, the web-based
documentation server godoc
associates example
functions with the function or package they exemplify, so
ExampleIsPalindrome
would be shown with the documentation for
the IsPalindrome
function, and an example function called just
Example
would be associated with the word
package as a whole.
The second purpose is that examples are executable tests run by
go test
. If the
example function contains a final // Output:
comment like
the one above, the test driver will
execute the function and check that what it printed to its standard
output matches the text within the comment.
The third purpose of an example is hands-on experimentation.
The godoc
server at golang.org
uses the Go Playground to let the user edit
and run each
example function from within a web browser, as shown in Figure 11.4.
This is often the fastest way to get a feel for a particular function
or language feature.
The final two chapters of the book examine the reflect
and
unsafe
packages, which few Go programmers regularly use—and
even fewer need to use.
If you haven’t written any substantial Go programs yet,
now would be a good time to do that.
18.191.5.239