Macro invocation in Rustdoc and generating examples

Hello,
I'm looking for a way to create documentation tests that showcase, e.g. a JSON example in the docs based on a struct inside the doc test itself.

The idea behind all this is to document a REST API using Rust docs and have examples for the JSON or request queries that the given calls expect.
I could not find, however, if it's possible for the #[doc] macro to capture the doc test scope and create those examples so that this invocation of the macro:

///
/// # Examples
///
/// ```
/// use serde::Serialize;
///
/// #[derive(Debug, Clone, Serialize)]
/// struct Struct { field: u32 }
///
/// fn main() {
/// let my_struct = Struct { field: 42 };
///
#[doc = doc_json!(&my_struct)]
///
/// }
///

Result in documentation resembling something like this:

/// # Examples
///
/// ```
/// use serde::Serialize;
///
/// #[derive(Debug, Clone, Serialize)]
/// struct Struct { field: u32 }
///
/// fn main() {
/// let my_struct = Struct { field: 42 };
///
/// let json = serde_json::json!({
/// "field": 42
/// });
/// let struct_deser = serde_json::from_value::<Struct>(json).expect("Should deserialize");
///
/// assert_eq!(&my_struct, &struct_deser);
// }

I'm aware of the crates that try to address something similar:

PS: I'm very new to macros so I'm struggling to find if this is even possible at the moment.

As far as the macro (and rustc, even) is concerned, the doctests are just text. A macro can generate whatever strings it wants. No scope is involved.

However, if you're looking to capture information about the type declaration — you will need to use an attribute macro which receives the struct definition as input.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.