Reflexion around unit tests and documentation example

I have a dilemma. In rust, since the code example are compiled and run with cargo tests, we can have working examples in the documentation. On the other hand, unit tests serve more or less the same goal in my opinion. In both cases they document how a function should behave, and how it can be used.

I wanted to document a function with 6-7 examples (it takes two closures witch means that a lot of use cases can be covered by this function). I could either write those test as unit tests, and they are going to be run with cargo test. On the other hand, I could write those tests in the documentation. Witch one should I prefer?

Another way to see at this problem could be to tag unit-tests (maybe with something like a new attribute #[cfg(documentation). Do you think this could be a valuable capability to add to cargo doc?

I was looking for a way to perfect my rust skill, so I will either continue to document my function or hack in cargo/rustc (I don't know where that modification need to be done).

Put them in the documentation if you feel they help explain the use of the type. Put them in unit tests if they're only there to detect bugs.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.