如何将 Rust 宏变量嵌入到文档中? [英] How to embed a Rust macro variable into documentation?

查看:41
本文介绍了如何将 Rust 宏变量嵌入到文档中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在宏生成的文档中使用一个宏变量:

I'd like to use a macro variable in the macro-generated documentation:

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

        }
    };
}

但是,变量不会被替换.我也尝试使用 #[doc] 属性:

However, the variable won't be substituted. I also tried using the #[doc] attribute:

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

        }
    };
}

这个竟然解析失败:unexpected token: 'concat'

推荐答案

这可以使用递归宏来完成:

This can be done using a recursive macro:

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

    ($name:tt) => {
        impl_foo!($name, stringify!($name));
    };
}

impl_foo!(u32);


fn main() {
    println!("Hello, world!");
}

呈现为:

这篇关于如何将 Rust 宏变量嵌入到文档中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆