#documentation #rustdoc #example

include-doc

Include examples in your Rustdocs

7 releases

0.2.1 Aug 1, 2023
0.2.0 Jul 31, 2023
0.1.2 Jul 30, 2023
0.0.2 Jan 31, 2023

#4 in #example

Download history 14/week @ 2023-12-11 24/week @ 2024-01-08 9/week @ 2024-01-15 3/week @ 2024-01-29 1/week @ 2024-02-12 1/week @ 2024-02-19 39/week @ 2024-02-26 37/week @ 2024-03-04 25/week @ 2024-03-11 9/week @ 2024-03-18 8/week @ 2024-03-25

84 downloads per month
Used in 3 crates

MIT/Apache

8KB

Include Doc

tests crates.io Documentation MIT/Apache-2 licensed

Include examples in your Rustdocs.

Features

  • Write and maintain your examples in a normal Rust file, with full editor support.
  • Automatically hide imports.
  • Put many examples into one file, and choose the parts of the file to include. This helps avoid duplicated boilerplate for imports and setup code.

See the crate docs for examples.


lib.rs:

Include Rust source files as doctests.

Examples

Using source_file!

We'll write our example in the file examples/my_example.rs, and use source_file! to add the example to our documentation. The contents of examples/my_example.rs are:

Using #[doc = source_file!("examples/my_example.rs")] will hide imports and include the body of the main function, leaving us with:

Using function_body!

function_body! is similar to source_file!, but allows us to specify which function body to use as the doctest. This reduces boilerplate for imports and supporting code, as we can put many examples in one file. We can also specify which parts of the supporting code to include.

Usage is:

include_doc::function_body!(
    "example.rs",
    example_fn,
    [fn_dependency, StructDependency, etc]
);

In tests/doc.rs, we've put 2 examples, my_first_example and my_second_example. There are 2 different setup functions, but both use MyStruct. Here's the contents of tests/doc.rs:

We want to include only the example code and dependencies for my_first_example, so we write #[doc = function_body!("tests/doc.rs", my_first_example, [MyStruct, setup_first_example])], giving us:

For my_second_example, we use #[doc = function_body!("tests/doc.rs", my_second_example, [MyStruct, setup_second_example])], giving:

Dependencies

~4–14MB
~153K SLoC