CodeBlanks Logo Icon CodeBlanks

Comments

Document your code with // and /* */ comments.

Comments

Rust has three kinds of comments: // single line, /* ... */ multi-line, and /// doc comments. Doc comments become HTML documentation with cargo doc, and the code examples inside them run as tests.

/// İki sayıyı toplar.
/// ```
/// assert_eq!(topla(2, 3), 5);
/// ```
fn topla(a: i32, b: i32) -> i32 {
    a + b // the result is returned as an expression
}

Good comments

A good comment explains why the code does something, not what it does. The code itself should already say what it does through readable names. //! at the top of a file or crate documents the whole module.

// Bad: increment i
i += 1;

// Good: skip the header line
i += 1;

Practice Documented function

Write a fn kare(n: i32) -> i32 function documented with ///, and in main call println!("{}", kare(9)); under a // comment.

Starter code

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

Sample solution

main.rs
/// Sayının karesini döndürür.
fn kare(n: i32) -> i32 {
    n * n
}

fn main() {
    // 9'un karesini yazdır
    println!("{}", kare(9));
}

Expected output

81

Questions and answers

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

1 What happens to code examples in <code>///</code> comments?

  • Only the IDE shows them
  • They run as tests with cargo test Correct answer
  • They are ignored
  • They cause a compile error

Explanation: This feature, called doc tests, guarantees that the examples in the documentation stay current and correct.

2 Doc comment

Question
____ Dairenin alanını hesaplar.
fn alan(r: f64) -> f64 { 3.14 * r * r }
Answer
/// Dairenin alanını hesaplar.
fn alan(r: f64) -> f64 { 3.14 * r * r }

Explanation: Text after /// becomes the function's documentation.

3 Comment kind

Term Meaning
// Single line
/* */ Multi-line
/// Item documentation
//! Module documentation

All lessons in Beginner