rustrustdoc

How to document Rust function arguments?


rustdoc allows you to document struct fields and enum variants by including a doc comment above each line:

enum Choices {
  /// The first choice.
  First,
  /// The second choice.
  Second,
}

struct Person {
  /// The person's name.
  name: String,
  /// The person's age.
  age: u8,
}

These will show up with nice formatting in the HTML generated by rustdoc. However, I haven't seen any way of making similar nicely-formatted documents for function arguments. Is there an "official" way to document them or do you just have to describe them freeform in the function's main documentation section?


Solution

  • According to the rust documentation, function docs are formatted like this:

    #![crate_name = "doc"]
    
    /// A human being is represented here
    pub struct Person {
        /// A person must have a name, no matter how much Juliet may hate it
        name: String,
    }
    
    impl Person {
        /// Returns a person with the name given them
        ///
        /// # Arguments
        ///
        /// * `name` - A string slice that holds the name of the person
        ///
        /// # Examples
        ///
        /// ```
        /// // You can have rust code between fences inside the comments
        /// // If you pass --test to `rustdoc`, it will even test it for you!
        /// use doc::Person;
        /// let person = Person::new("name");
        /// ```
        pub fn new(name: &str) -> Person {
            Person {
                name: name.to_string(),
            }
        }
    
        /// Gives a friendly hello!
        ///
        /// Says "Hello, [name]" to the `Person` it is called on.
        pub fn hello(& self) {
            println!("Hello, {}!", self.name);
        }
    }
    
    fn main() {
        let john = Person::new("John");
    
        john.hello();
    }