有什么方法可以在文档注释中内联一个常量(由 cargo doc 呈现)?

Is there any way to inline a const inside a doc comment (rendered by cargo doc)?

使用“默认”构造函数,记录什么是……默认值可能很有用。如果这是在文档中以文本方式定义并单独定义为文字或静态/常量,则两者可能会不同步:

impl Foo {
    /// Creates a [Foo] with a `bar` of 3.
    fn new() -> Foo { Foo::new_with_bar(5) }
    /// Creates a [Foo] with the provided `bar`.
    fn new_with_bar(bar: usize) -> Foo { Foo { bar } }
}

可以将文字提取为 const 或 static,然后 link 到那个,但是 reader 必须通过间接寻址知道值是什么,并且 const / static 必须是 pubcargo doc 抱怨并拒绝 link 它。

有什么方法可以替换 文档字符串中的 const 值而不是 link 吗?或者其他一些可以避免间接寻址的方法?又名

const DEFAULT_BAR: usize = 5
impl Foo {
    /// Creates a [Foo] with a `bar` of ???DEFAULT_BAR???.
    fn new() -> Foo { Foo::new_with_bar(DEFAULT_BAR) }
}

应呈现为:

pub fn new() -> Foo

Creates a Foo with a bar of 5.

虽然类似,但似乎并不适用于此。 [doc] 抱怨在给定名称作为参数(即使是 const str)时出现意外标记,我不知道包装宏是否可以强制替换 const。

在稳定版中,没有一个真正简单的解决方案可以做到这一点,而不需要为每个 type/method 使用专门的宏。因此,最简单的方法是回退到使用 const DEFAULT_BAR 并在文档中引用它(您希望避免这种情况。)


但是,有一个相当新的夜间功能 extended_key_value_attributes (see issue #78835 and PR 78837。)

除了需要最新的夜间构建之一。用于您的用例(在当前状态下)也会稍微麻烦一些。这是因为它要么要求使用文字,要么不使用 const DEFAULT_BAR。或者,您可以使用扩展为 5 的宏,这是一种麻烦的解决方案。

#![feature(extended_key_value_attributes)]

struct Foo {
    bar: usize,
}

macro_rules! default_bar {
    () => {
        5
    };
}

impl Foo {
    /// Creates a [Foo] with a `bar` of
    #[doc = concat!(default_bar!(), ".")]
    fn new() -> Foo {
        Foo::new_with_bar(default_bar!())
    }

    /// Creates a [Foo] with the provided `bar`.
    fn new_with_bar(bar: usize) -> Foo {
        Foo { bar }
    }
}

以上适用于 rustc 1.50.0-nightly (bb1fbbf84 2020-12-22)

请注意,您必须使用 concat!,否则 default_bar 需要扩展为字符串。所以如果你不需要例如".",那么就使用一个空字符串,例如concat!("", default_bar!()).

这适用于 Rust 1.47:

struct Foo { bar: usize }

macro_rules! impl_foo {
    ($bar_def:expr) => { impl_foo!(@ $bar_def, stringify!($bar_def)); };
    (@ $bar_def:expr, $bar_def_str:expr) => {
        impl Foo {
            /// Creates a [Foo] with a `bar` of
            #[doc = $bar_def_str]
            ///.
            fn new() -> Foo { Foo::new_with_bar($bar_def) }

            /// Creates a [Foo] with the provided `bar`.
            fn new_with_bar(bar: usize) -> Foo { Foo { bar } }
        }
    }
}

impl_foo!(3);

您可以使用 paste 来避免重定向:

use paste::paste;

struct Foo { bar: usize }

macro_rules! impl_foo {
    ($bar_def:expr) => {
        paste! {
            impl Foo {
                #[doc = "Creates a [Foo] with a `bar` of " $bar_def "."]
                fn new() -> Foo { Foo::new_with_bar($bar_def) }

                /// Creates a [Foo] with the provided `bar`.
                fn new_with_bar(bar: usize) -> Foo { Foo { bar } }
            }
        }
    }
}

impl_foo!(3);

将来,您可以使用 #![feature(extended_key_value_attributes)], as described in .

跳过宏中的重定向(或 paste! 的用法)

另请参阅:

  • doc-comment crate,它使用此技巧允许使用外部 Markdown 文件记录项目。