O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Documentation tests

It's often a good style to include examples in your documentation. There's a risk with such examples, though: your code might change and you might forget to update your documentation. Documentation tests help with that. They make the example code part of the unit test suite, which means that the examples run every time you run your unit tests, thus making forgetfulness painful earlier.

Documentation tests are included with your actual code, and come in two forms:

  • Module-level at the start of the module, marked by //!
  • Function-level before a function, marked by ///

Doctests are executed via Cargo, so we'll need to make our sum function an actual project to try these out:

// sum-with-doctest/src/lib.rs //! This crate ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required