How to embed Rust macro in the documentation?

I want to use the macro in macro-generated documentation:

macro_rules! impl_foo {
    ($name:ident) => {
        /// Returns a new `$name`.
        fn myfoo() -> $name {

        }
    };
}

However, the variable will not be replaced. I also tried using the attribute #[doc]:

macro_rules! impl_foo {
    ($name:ident) => {
        #[doc = concat!("Returns a new `", $name, "`.")]
        fn myfoo() -> $name {

        }
    };
}

This one can't even parse: unexpected token: 'concat'

+4
source share
1 answer

As far as I know, the best you can do requires some repetition:

macro_rules! impl_foo {
    ($name:ident, $sname:expr) => {
        #[doc = "Returns a new `"]
        #[doc = $sname]
        #[doc = "`."]
        fn myfoo() -> $name {
            42
        }
    };
}

impl_foo!(u32, "u32");

which is displayed as:

Example from rustdoc

+5
source

Source: https://habr.com/ru/post/1674594/


All Articles