Documenting a function created with a macro in Rust [duplicate]

我怕爱的太早我们不能终老 提交于 2021-02-08 15:13:38

问题


I tried to do

#![deny(missing_docs)]

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(())
});

with:

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?


回答1:


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
}

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



来源:https://stackoverflow.com/questions/41361897/documenting-a-function-created-with-a-macro-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!