4.2.4 Document Testing
Nothing is better than a document with an example. There is nothing worse than the inability to work, because it is possible that the code in the document has been modified. To do this, rust supports automated testing of our sample code. Let's look at an example of a flesh-and-blood src/lib.rs:
//! Theàdder ' crate provides functions that add numbers to other numbers.
//!
//! # Examples
//!
//! ```
//! assert_eq! (4, Adder::add_two (2));
//! ```
This function adds the argument.
///
# Examples
///
/// ```
Use Adder::add_two;
///
assert_eq! (4, Add_two ' 2));
/// ```
PUB fn Add_two (a:i32), i32 {
A + 2
}
#[cfg (Test)]
MoD Tests {
Use super::*;
#[test]
fn It_works () {
assert_eq! (4, Add_two (2));
}
}
Note that the comment at the module level is//!, and the comment at the function level is///. Rust annotations support annotations using Markdown, which is customary to use #example to start the example.
Run this test:
Now we have 3 tests! Note the name of the document test: _0 is generated when the module is tested, so add_two_0 is the function test. The name will automatically grow, such as add_two_1 and so on.
Page 83
4.3-piece compilation
Rust has a special property, #[cfg], and you can control the compiler by its identity in two ways:
#[cfg (foo)]
#[cfg (bar= "Baz")]
It also has some help options:
#[cfg (Any (unit, Windows))]
#[cfg (All (unit, target_pointer_width= "32"))]
#[cfg (not (foo))]
can also be nested:
#[cfg (No (Unix), All (target_os= "MacOS", Target_arch = "PowerPC"))]
As for how to enable and disable these switches, you can try cargo and have a [features] property in the Cargo.toml file:
[Features] #no features by DefaultDefault = []
# the "Secure-password" feature depands on the bcrypt Package.secure-password = ["Bcrypt"]
If you set this up, cargo will pass an identity to RUSTC:
--cfg feature= "${feature_name}"
Together, these CFG tags determine which code is activated and which code is compiled. Look at this code:
Page 84
#[cfg (feature = "foo") mod foo {}
If we compile with cargo build--feature "foo", it will send RUSTC a--cfg feature "foo" and the output will have the MoD Foo code. If we use the generic cargo build without passing any parameters, Then the Foo module will not exist in the code.
4.3.1 cfg_attr
You can set another CFG variable cfg_attr:
#{cfg_attr (A, b)]
It is the same as this command: When a is set by the CFG property, then use #[b].
4.3.2 cfg!
The cfg! syntax can be used in code:
If cfg! (Target_os = "Mac_os") | | Cfg! (Target_os = "ios") {println! ("Think different!");}
will be replaced with true or false at run time, depending on the configuration of the machine.
Rust Chinese Translation 17