有没有办法在文档注释中内联常量(由货物文档呈现)?

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

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 并链接到它,但是读者必须通过间接知道值是什么,并且 const / static 必须是pubcargo doc抱怨并拒绝链接到它。

有没有办法替换文档字符串中的 const 值而不是链接到它?或者其他一些可以避免间接的方法?又名

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

创建一个a为 5的Foobar

虽然类似,如何将 Rust 宏变量嵌入到文档中?似乎不适用于这里。[doc]当将名称作为参数(甚至是 const str)时,会抱怨意外的标记,我不知道包装宏是否可以强制替换 const。

回答

在稳定版上,这并不是一个简单的解决方案,不需要为每种类型/方法使用专门的宏。因此,最简单的方法是回退到使用 aconst DEFAULT_BAR并在文档中引用它(您想避免这种情况。)


但是,有一个相当新的夜间功能extended_key_value_attributes(请参阅问题 #78835和PR 78837。)

除了需要最新的每晚构建之一。用于您的用例(在当前状态下)也会有点麻烦。这是因为它要么需要使用文字,不包括 using 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需要扩展为字符串。因此,如果您不需要 eg ".",那么只需使用一个空字符串,例如concat!("", default_bar!()).


以上是有没有办法在文档注释中内联常量(由货物文档呈现)?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>