Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

testing

go

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! :)

like image 592
Charlie Parker Avatar asked Jun 26 '14 02:06

Charlie Parker


1 Answers

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/

like image 120
ANisus Avatar answered Nov 09 '22 16:11

ANisus