如果我在文档注释中留下一个空行,后跟 4 个空格的缩进,那么货物会将其解释为文档测试,并在我运行货物测试时给我一个失败。关于解释这一点的文档评论和测试,我应该了解哪些信息?
这是 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);
}
}
如果我运行货物测试,这是输出:
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'
如果我从文档注释中“note”之前的缩进中删除一个空格,那么一切都会按预期进行:
/// 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
这里到底发生了什么?
4 个空格的缩进相当于用反引号括起来 - 更多信息可以在语法参考
找到