» Quick Introduction to Rust » 2. Advanced » 2.9 Documentation

Documentation

Use cargo doc to build documentation. Use cargo test to run all tests (including doc tests), and cargo test --doc to only run doc tests.

Doc Comments

Comments are denoted by a ///, and support markdown.

/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// let result = add_numbers(2, 3);
/// assert_eq!(result, 5);
/// ```
///
/// # Arguments
///
/// * `a` - The first number.
/// * `b` - The second number.
///
/// # Returns
///
/// The sum of `a` and `b`.
///
/// # Panics
///
/// This function will panic if the sum overflows a `u32`.
///
/// # Safety
///
/// This function is safe to call with any valid values of `a` and `b`.
///
/// # Notes
///
/// This is a simple example for demonstration purposes.
///
/// # Examples
///
/// ```
/// let result = add_numbers(10, 20);
/// println!("The sum is: {}", result);
/// ```
fn add_numbers(a: u32, b: u32) -> u32 {
    a + b
}

fn main() {
    // Example usage of the function
    let result = add_numbers(2, 3);
    println!("The sum is: {}", result);
}

Doc Attributes

inline

#[doc(inline)] is used to include the documentation of the target item when documenting another item. For example:

/// # Examples
/// ```
/// use my_crate::my_module::add_numbers;
/// let result = add_numbers(2, 3);
/// assert_eq!(result, 5);
/// ```
#[doc(inline)]
pub use my_crate::my_module::add_numbers;

mod my_module {
   /// Adds two numbers together.
   pub fn add_numbers(a: u32, b: u32) -> u32 {
       a + b
   }
}

hidden

#[doc(hidden)] is used to hide an item from the generated documentation. It can be useful when you want to include something in the code but don't want it to be part of the public API documentation.

#[doc(hidden)]
pub fn internal_function() {
    // implementation details
}

/// This function is part of the public API.
pub fn public_function() {
    // ...
}