Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are Go example functions?

Tags:

testing

go

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?

like image 955
Calin Avatar asked Mar 19 '15 10:03

Calin


1 Answers

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

like image 95
icza Avatar answered Oct 03 '22 17:10

icza