What are Go example functions?

huangapple go评论87阅读模式
英文:

What are Go example functions?

问题

Go的测试包中提到了示例函数,例如:

func Example() { ... }
func ExampleF() { ... }
func ExampleT() { ... }
func ExampleT_M() { ... }

这些函数的含义和用法是什么?

英文:

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

得分: 12

示例函数是对包、函数或其他代码进行文档化的用法示例。示例函数将以源代码形式包含在生成的godoc中(而其他函数则不包含),并进行适当的格式化和一些处理。例如,如果示例函数的最后一行包含输出,格式如下:

func ExampleExamples_output() {
    fmt.Println("Hello")
    // Output: Hello
}

指定输出的最后一行将被剥离并在单独的块中呈现,可以在这里看到:示例(输出)

此外,如果提供了输出:运行包的测试套件(例如使用go test)还会执行示例函数,无需进一步安排。Go会将示例函数的输出与最后一行注释中指定的输出进行比较,结果将确定此示例函数是否作为“测试”通过。如果示例函数中未指定输出,go test将仅编译它但不执行它。

请查看此页面:package godoctricks

还有一篇关于示例函数的博客文章:

在Go中进行可测试的示例

英文:

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

huangapple
  • 本文由 发表于 2015年3月19日 18:01:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/29141579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定