记录在Rust中使用宏创建的函数 [英] Documenting a function created with a macro in Rust

查看:47
本文介绍了记录在Rust中使用宏创建的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做

#![deny(missing_docs)]

在Rust中.而且我发现,使用这样的宏创建函数时,会忽略///注释:

in Rust. And I found that /// comments are just ignored when a function is created with a macro like this:

/// docs
py_module_initializer!(libx, initlibx PyInit_libx |py, m| {
    Ok(())
});

具有:

error: missing documentation for a function
113 | py_module_initializer!(libx initlibx PyInit_libx |py, m| {
    | ^

我认为宏只会在///之后添加一个函数定义.怎么了?

I thought a macro will just add a function definition after ///. What is wrong here?

推荐答案

您的文档注释引用了宏调用,在您的情况下这是没有用的.要记录生成的函数,您必须将文档注释写入宏定义,或者将宏更改为也接受文档注释.我们来看一下:

Your doc comment refers to the macro invocation, which is useless in your case. To document the generated functions you have to write the doc comment into the macro definition or change your macro to also accept doc comments. Let's take a look at this:

#![deny(missing_docs)]
//! crate docs

macro_rules! gen_fn {
    ($name:ident) => {
        /// generic doc comment... not very useful
        pub fn $name() {}
    }
}

gen_fn!(a);
gen_fn!(b);

这可行,但这不是最佳解决方案,因为所有生成的函数的文档注释均相同.如果要记录每个生成的函数,则必须更改宏:

This works, but it's not the best solution, because doc comments are the same for all generated functions. If you want to document each generated function, you have to change the macro:

macro_rules! gen_fn {
    ($(#[$attr:meta])* => $name:ident) => {
        $(#[$attr])*
        pub fn $name() {}
    }
}

gen_fn!{
    /// Doc comment for a
    => a
}

这行得通,因为doc注释在内部被转换为#[doc(...)] 属性.您可以在此处找到更多信息.

This works, because doc comments are converted to the #[doc(...)] attribute internally. You can find more information about that here.

这篇关于记录在Rust中使用宏创建的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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