【问题标题】:Extra spaces in rust doc comment gets interpreted as doc testrust doc 注释中的额外空格被解释为 doc test
【发布时间】:2021-06-23 15:24:05
【问题描述】:

看来,如果我在 doc 注释中留下一个空行,然后缩进 4 个空格,那么 cargo 会将其解释为 doc 测试,并在我运行 cargo test 时给我一个失败。关于解释这一点的 doc cmets 和测试,我应该知道些什么?

这是 lib.rs 中的一些示例代码:

/// This is a great function.
/// y: a very dangerous option.
///
///     note: Use None for y or you'll be sorry.
pub fn thing(x: i32, y: Option<i32>) -> i32 {
    if y.is_some() {
        println!("explode!");
    }
    x
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_thing() {
        assert_eq!(thing(5, None), 5);
    }
}

如果我运行 cargo test,输出如下:

    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests (target/debug/deps/test_docs-28c699ad5df73c48)

running 1 test
test tests::test_thing ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests test_docs

running 1 test
test src/lib.rs - thing (line 5) ... FAILED

failures:

---- src/lib.rs - thing (line 5) stdout ----
error: expected one of `!`, `(`, `.`, `::`, `;`, `<`, `?`, or `}`, found `None`
 --> src/lib.rs:6:11
  |
3 | note: Use None for y or you'll be sorry.
  |     -     ^^^^ expected one of 8 possible tokens
  |     |
  |     tried to parse a type due to this

error: aborting due to previous error

Couldn't compile the test.

failures:
    src/lib.rs - thing (line 5)

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s

error: test failed, to rerun pass '--doc'

如果我从文档注释中“注释”之前的缩进中删除一个空格,那么一切都会按预期工作:

/// This is a great function.
/// y: a very dangerous option.
///
///    note: Use None for y or you'll be sorry.
pub fn thing(x: i32, y: Option<i32>) -> i32 {
    if y.is_some() {
        println!("explode!");
    }
    x
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_thing() {
        assert_eq!(thing(5, None), 5);
    }
}

输出:

Compiling test_docs v0.1.0 (/Users/cleverpiggy/test_docs)
    Finished test [unoptimized + debuginfo] target(s) in 0.34s
     Running unittests (target/debug/deps/test_docs-28c699ad5df73c48)

running 1 test
test tests::test_thing ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests test_docs

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

这到底是怎么回事?

【问题讨论】:

    标签: rust


    【解决方案1】:

    4个空格的缩进相当于用反引号包围 - 更多信息可以在the syntax reference找到

    【讨论】:

      猜你喜欢
      • 2013-10-02
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 2015-08-24
      • 2011-03-17
      相关资源
      最近更新 更多