11

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?

Calin
  • 2,110
  • 1
  • 21
  • 36
  • I see nothing unclear in the documentation you link to. IMO, your question is equivalent to something like "the spec mentions `int` what is the meaning and use case for it?" i.e. so vague/basic or with no real question as to be useless. – Dave C Mar 19 '15 at 16:05
  • 1
    @icza's answer was spot on. The docs don't mention that example functions are used with `godoc`, so it was unclear to me what you would use them for. – Calin Mar 19 '15 at 16:21

1 Answers1

12

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

icza
  • 389,944
  • 63
  • 907
  • 827
  • one extra stupid syntactical point : in the `// Output:` comment, there must be no space between the word `Output` and the `:`. Otherwise the Example function isn't treated as a test case. – LeGEC Apr 13 '22 at 05:05