What are Go example functions?

99封情书 提交于 2021-02-18 21:58:26

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/29141579/what-are-go-example-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!