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

标签 rust doc 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 并链接到它,但是读者必须通过间接知道值是什么,并且 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

Creates a Foo with a bar of 5.


虽然相似,How to embed a Rust macro variable into documentation?似乎不适用于这里。 [doc]当将名称作为参数(甚至是 const str)时,会提示意外的标记,我不知道包装宏是否可以强制替换 const。

最佳答案

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

然而,有一个相当新的夜间功能 extended_key_value_attributes (见 issue #78835PR 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 - 有没有办法在文档注释中内联常量(由 cargo 文档呈现)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65426621/

相关文章:

用于生成 .doc 或 .docx 文档文件的 Perl 模块

rust - 生成 rustdoc 时如何使用本地文件作为 crate Logo ?

rust - 枚举值的向量会产生所有权问题

generics - 如何使用通用方法参数创建可散列特征对象/特征对象?

rust - 为什么不允许在格式中重复使用相同的值!宏观

rust - Serde 跳过字段序列化取决于 "global"运行时条件

c# - 以编程方式将 Doc 转换为 Docx bug

c# - 使用 C# 从 Word 文档中获取以特定模式开头的单词