The Go testing package mentions example functions as in:
func Example() { ... }
func ExampleF() { ... }
func ExampleT() { ... }
func ExampleT_M() { ... }
What is the meaning and use case for these?
Example functions are usage examples of a package or functions or other code you're documenting. Example functions will be included in the generated godoc in source form (while other functions are not), with proper formatting, also some processing applied, for example if last line of the example function contains output in the format of:
func ExampleExamples_output() {
fmt.Println("Hello")
// Output: Hello
}
The last line specifying the output will be stripped and rendered in a separate block, as can be seen here: Example (Output).
Also if the output is provided: running the package's test suite (e.g. with go test
) also executes example functions with no further arrangement from you, and Go compares the output of the example function with the output specified in the last comment line - the result of this will determine if this example function as "test" passes. If output is not specified in the example function, go test
will only compile it but will not execute it.
Check out this page: package godoctricks
Also a blog article has been published about Example functions:
Testable Examples in Go
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With