As can be seen throughout most code examples given in this chapter, Rust code can be annotated with comments that are ignored during compilation and execution.
Quick, single-line comments are denoted with a double forward slash (//):
fn main() {
let mut vector: Vec<isize> = Vec::new(); // initialising function for vector structs
vector.push(5); // function for appending an element to a vector
dbg!(vector); // macro that prints the vector in debug format
}
If a more detailed description is required for a piece of code, Rust allows for doc comments, indicated with a triple forward slash (///):
fn main() {
for i in 0..30 {
println!("{}", fibonacci(i));
}
}
/// A function that takes a signed 32-bit integer as an argument
/// and also returns a signed 32-bit integer.
///
/// Finds the zero-indexed nth term of the Fibonacci sequence.
///
/// The function is recursive; if the integer is not zero or one,
/// it will repeatedly call itself with smaller numbers less than
/// n in order to find the sum of each term of the sequence before
/// the nth.
///
fn fibonacci(n: i32) -> i32 {
if n == 0 {
return 0;
} else if n == 1 {
return 1;
} else {
fibonacci(n-1) + fibonacci(n-2)
}
}
Doc comments also support Markdown, allowing for division into titles, subtitles and code block examples if the documentation is being read in a text editor that supports Markdown:
fn main() {
for i in 0..30 {
println!("{}", fibonacci(i));
}
}
/// # Fibonacci function
///
/// A function that takes a signed 32-bit integer as an argument
/// and also returns a signed 32-bit integer.
///
/// Finds the zero-indexed nth term of the Fibonacci sequence.
///
/// ## Example
///
/// ```fibonacci(10)``` will return 55, the tenth term of the
/// sequence (assuming that there is a 0th term).
///
fn fibonacci(n: i32) -> i32 {
if n == 0 {
return 0;
} else if n == 1 {
return 1;
} else {
fibonacci(n-1) + fibonacci(n-2)
}
}