使用“默认”构造函数,记录......默认值是什么会很有用。如果这是在文档中以文本方式定义并单独定义为文字或静态/常量,则两者可能会不同步:
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 必须是 pub
或 cargo 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 #78835 和 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 - 有没有办法在文档注释中内联常量(由 cargo 文档呈现)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65426621/