[][src]Crate doc_comment

The point of this (small) crate is to allow you to add doc comments from macros or to test external markdown files' code blocks through rustdoc.

Including file(s) for testing

Let's assume you want to test code examples in your README.md file which looks like this:

# A crate

Here is a code example:

```rust
let x = 2;
assert!(x != 0);
```

You can use the doc_comment! macro to test it like this:

extern crate doc_comment;

// When running `cargo test`, rustdoc will check this file as well.
doc_comment::doctest!("../README.md");

Please also note that you can use #[cfg(doctest)]:

#[cfg(doctest)]
doc_comment::doctest!("../README.md");

In this case, the examples in the README.md file will only be run on cargo test. You can find more information about #[cfg(doctest)] in this blogpost.

Generic documentation

Now let's imagine you want to write documentation once for multiple types but still having examples specific to each type:

// The macro which generates types
macro_rules! gen_types {
    ($tyname:ident) => {
        /// This is a wonderful generated struct!
        ///
        /// You can use it as follow:
        ///
        /// ```
        /// let x = FirstOne {
        ///     field1: 0,
        ///     field2: 0,
        ///     field3: 0,
        ///     field4: 0,
        /// };
        ///
        /// println!("Created a new instance of FirstOne: {:?}", x);
        /// ```
        #[derive(Debug)]
        pub struct $tyname {
            pub field1: u8,
            pub field2: u16,
            pub field3: u32,
            pub field4: u64,
        }
    }
}

// Now let's actually generate types:
gen_types!(FirstOne);
gen_types!(SecondOne);
gen_types!(Another);

So now we have created three structs with different names, but they all have the exact same documentation, which is an issue for any structs not called FirstOne. That's where doc_comment! macro comes in handy!

Let's rewrite the gen_types! macro:

// Of course, we need to import the `doc_comment` macro:
extern crate doc_comment;

macro_rules! gen_types {
    ($tyname:ident) => {
        #[doc_comment::doc_comment("This is a wonderful generated struct!

You can use it as follow:

```
let x = ", $tyname, " {
    field1: 0,
    field2: 0,
    field3: 0,
    field4: 0,
};
println!(\"Created a new instance of ", $tyname, ": {:?}\", x);
```")]
        #[derive(Debug)]
        pub struct $tyname {
            pub field1: u8,
            pub field2: u16,
            pub field3: u32,
            pub field4: u64,
        }
    }
}

gen_types!(FirstOne);
gen_types!(SecondOne);
gen_types!(Another);

Now each struct has doc which match itself!

Macros

doctest

This proc macro provides a simpler way to test an outer markdown file.

Attribute Macros

doc_comment