Exercise - Write documentation tests
In this exercise, you'll create documentation tests in the following code snippet for the functions div
and sub
.
For the div
function, write the following documentation tests:
- Assert that
10
divided by2
equals5
. - Assert that
6
divided by3
equals2
. - Assert that
10
divided by0
panics.
For the sub
function, write the following documentation tests:
- Assert that
9
subtracted by2
equals7
. - Assert that
6
subtracted by9
equals-3
.
/// This function divides two numbers.
///
/// # Example #1: 10 / 2 == 5
///
/// ```
/// let result = doctests_exercise::div(...); // TODO: finish this test!
/// assert_eq!(result, 2);
/// ```
///
/// # Example #2: 6 / 3 = 2
///
/// ```
/// TODO: Write this doctest!
/// ```
///
/// # Panics
///
/// The function panics if the second argument is zero.
///
/// ```rust,should_panic
/// // panics on division by zero
/// TODO: Write this doctest!
/// ```
pub fn div(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("Divide-by-zero error");
}
a / b
}
/// This function subtracts two numbers.
///
/// # Example #1: 9 - 2 == 7
///
/// ```
/// TODO: Write this doctest!
/// ```
///
/// # Example #2: 6 - 9 == -3
///
/// ```
/// TODO: Write this doctest!
/// ```
pub fn sub(a: i32, b: i32) -> i32 {
a - b
}
Remember to create the project in your computer first because documentation tests are only available for library crates. You can run the following commands in your terminal to accomplish this objective:
$ cargo new --lib doctests_exercise
$ cd doctests_exercise
The name of the crate must prefix the name of the function because it's already filled in for the first assignment of this exercise.
To find a complete version of this exercise, see this Rust Playground link.