什么是Go示例函数? [英] What are Go example functions?

查看:50
本文介绍了什么是Go示例函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

示例函数是您要记录的程序包或函数或其他代码的用法示例.示例函数将以源代码形式包含在生成的godoc中(而其他函数则未包含),格式正确,并且还会进行一些处理,例如,如果示例函数的最后一行包含以下格式的输出:

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).

如果提供了输出,则:运行程序包的测试套件(例如,使用 go test )也将执行示例函数,而无需您做进一步的安排,而Go将示例函数的输出与在最后一条注释行中指定的输出-其结果将确定此示例功能是否通过测试".如果在示例函数中未指定输出,则 go test 只会编译它,而不会执行它.

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.

查看此页面: 打包Godoctricks

Check out this page: package godoctricks

还发布了有关示例函数的博客文章:

Also a blog article has been published about Example functions:

Go中可测试的示例

这篇关于什么是Go示例函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆