Including example code in doc comments

I have a runnable example program that I would like to have in my crate's examples directory, as well as in the doc comment for my crate. The two should stay in sync. Is there any way to include the code from one in the other. Or alternatively have a way to run the program from a doc comment (even if it has no_run, since it isn't suitable to run as a test)?

It doesn't look very nice having attributes interspersed with your /// comments but the #[doc(include = "...")] attribute can do this.

// src/lib.rs

#![feature(external_doc)]

/// Here is my example:
///
/// ```rust
#[doc(include = "../examples/foo.rs")]
/// ```
pub fn foo() {
    println!("Hello, world!");
}

My example:

// examples/example.rs

fn main() {
    println!("Hello from examples/");
}

And this is what I see when running cargo doc:

DeepinScreenshot_select-area_20210213173931

5 Likes

From the tracking issue it seems like #[doc = include_str!("../examples/foo.rs")] might be preferred?

Unfortunately, both are still unstable. And with the latter, I get warning: doc comment contains an invalid Rust code block, although it seems to render correctly.

And what's worse, even if I do something like:

#![cfg_attr(docsrs, doc = include_str!("../examples/echo1.rs"))]

it won't compile on stable due to arbitrary expressions in key-value attributes being unstable.