CodeBlanks Logo Icon CodeBlanks

Doc test

Write doc tests with ///.

Doc tests

Code blocks in doc comments written with /// are run by cargo test. This way the examples in the docs never go stale:

/// Metni büyük harfe çevirir.
///
/// ```
/// assert_eq!(metin::buyuk_harf("rust"), "RUST");
/// ```
pub fn buyuk_harf(s: &str) -> String {
    s.to_uppercase()
}

cargo doc --open generates HTML docs from the same comments. Blocks meant only for display are marked with ```ignore or ```no_run.

Doc comment sections

Conventional headings guide the reader:

/// İki sayıyı böler.
///
/// # Örnekler
/// ```
/// assert_eq!(bol(10, 2), Some(5));
/// ```
///
/// # Hatalar
/// `b` sıfırsa `None` döner.
pub fn bol(a: i32, b: i32) -> Option<i32> { .. }

//! documents the module or crate it's inside; it's usually written at the top of lib.rs.

Practice Documented function

Inside mod metin, write pub fn buyuk_harf(s: &str) -> String with an example in a ``` code block in a /// doc comment. In main, print the result of metin::buyuk_harf("rust").

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
mod metin {
    /// Metni büyük harfe çevirir.
    ///
    /// ```
    /// assert_eq!(metin::buyuk_harf("rust"), "RUST");
    /// ```
    pub fn buyuk_harf(s: &str) -> String {
        s.to_uppercase()
    }
}

fn main() {
    println!("{}", metin::buyuk_harf("rust"));
}

Expected output

RUST

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 For which crates do doc tests run?

  • All files
  • None, they're run by hand
  • Library crates Correct answer
  • Only binary crates

Explanation: Doc tests are compiled as separate small programs using the library from outside.

2 Doc comment

Question
____ Metni büyük harfe çevirir.
pub fn buyuk_harf(s: &str) -> String {
    s.to_uppercase()
}
Answer
/// Metni büyük harfe çevirir.
pub fn buyuk_harf(s: &str) -> String {
    s.to_uppercase()
}

Explanation: /// documents the next item, and its code blocks are tested.

3 Syntax and meaning

Term Meaning
/// Item doc
//! Module doc
```ignore Not run
cargo doc Generates HTML docs

All lessons in Intermediate