“go(golang)测试框架中的“examples”有什么作用?”

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

What is the point of "examples" in the go (golang) testing framework?

问题

我最近在阅读Go测试框架中的测试和示例,但并不真正理解它们的用途。我看到文档中说:

> 该包还会运行和验证示例代码。示例函数可能包含一个以"Output:"开头的结尾行注释,该注释将与在运行测试时函数的标准输出进行比较。(比较会忽略前导和尾随空格。)

然而,我并不真正理解为什么会有这个功能。当我编写我的测试时,通过阅读单元测试和基准测试,应该已经非常清楚如何使用代码了。示例部分提供了什么额外的动机?对我来说,它似乎是多余的,但我相信Go的发明者们出于某种良好的原因而添加了它,特别是因为他们似乎通过设计语言来强调良好的编程实践。我希望能理解他们的动机,或者如何在Go项目中以积极的方式使用这部分语言! “go(golang)测试框架中的“examples”有什么作用?”

英文:

I was recently reading on testing and examples in the go testing framework and did not really understand what they were for. I see that the documentation says:

> The package also runs and verifies example code. Example functions may include a concluding line comment that begins with "Output:" and is compared with the standard output of the function when the tests are run. (The comparison ignores leading and trailing space.)

However, I don't really appreciate the reason that this would exist. As I write my tests, it seems that it should be more than clear how to use the code just by reading the unit tests and the benchmarks. What additional motivation does the example section provide? It seems redundant to me, however, I am sure that the inventors of go put it for a good reason, specially because they seem to empathizes good programming practice by the design of their language. I hope to understand either their motivation or how this part of language can be used in a positive way in a golang project! “go(golang)测试框架中的“examples”有什么作用?”

答案1

得分: 11

在Go语言中,源代码也用于生成文档。示例代码并不是用于测试,而是用于文档说明。通过编译示例代码,你可以确保它们对任何使用它们的人都能正常工作。

当使用golang.org浏览文档时,可以直接在浏览器中运行标准库中的示例代码。而godoc.org则会直接将你的示例代码链接到play.golang.org,你可以在那里尝试运行它。

有关示例或示例用法,请参见:http://golang.org/pkg/sort/

英文:

In Go, the source code is also used to generate documentation. Examples are not meant for testing but rather for the documentation. By having compiled examples, you can make sure they are working properly for anyone using them.

Examples found in the standard libraries can be run directly in the browser when using golang.org to browse the documentation. Godoc.org instead links your example code directly to play.golang.org where you can try it out.

As an example or Example usage, see: http://golang.org/pkg/sort/

huangapple
  • 本文由 发表于 2014年6月26日 10:01:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/24421326.html
匿名

发表评论

匿名网友

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

确定