【发布时间】:2018-10-23 01:02:57
【问题描述】:
我正在为一个模块编写文档,该模块具有由 Cargo 功能标志控制的一些选项。我希望始终显示此文档,以便 crate 的消费者知道它是可用的,但我只需要在启用该功能时运行示例。
lib.rs
//! This crate has common utility functions
//!
//! ```
//! assert_eq!(2, featureful::add_one(1));
//! ```
//!
//! You may also want to use the feature flag `solve_halting_problem`:
//!
//! ```
//! assert!(featureful::is_p_equal_to_np());
//! ```
pub fn add_one(a: i32) -> i32 {
a + 1
}
#[cfg(feature = "solve_halting_problem")]
pub fn is_p_equal_to_np() -> bool {
true
}
Cargo.toml
[package]
name = "featureful"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
[features]
solve_halting_problem = []
[dependencies]
在启用该功能的情况下运行会按预期运行两个 doctest:
$ cargo test --features=solve_halting_problem
Doc-tests featureful
running 2 tests
test src/lib.rs - (line 7) ... ok
test src/lib.rs - (line 3) ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
不使用该功能运行有错误:
$ cargo test
Doc-tests featureful
running 2 tests
test src/lib.rs - (line 7) ... FAILED
test src/lib.rs - (line 3) ... ok
failures:
---- src/lib.rs - (line 7) stdout ----
error[E0425]: cannot find function `is_p_equal_to_np` in module `featureful`
--> src/lib.rs:8:21
|
4 | assert!(featureful::is_p_equal_to_np());
| ^^^^^^^^^^^^^^^^ not found in `featureful`
```ignore 和 ```no_run 修饰符都适用于该功能是否启用,因此它们似乎没有用。
How would one achieve conditional compilation with Rust projects that have doctests? 很接近,但答案集中在随条件编译而变化的函数,而不是模块的文档。
【问题讨论】:
标签: rust automated-tests documentation conditional-compilation