英文:
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
还有一篇关于示例函数的博客文章:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论