Mastering Rust
上QQ阅读APP看书,第一时间看更新

Running examples with Cargo

To enable users to quickly get started with your crate, it's a good practice to communicate to users how to use your crate with code examples. Cargo standardize this practice, meaning that you can add an examples/ directory within your project root that can contain one or more .rs files, with a main function showing example usage of your crate.

The code under the examples/ directory can be run by using cargo run --examples <file_name>, where the filename is given without the .rs extension. To demonstrate this, we've added an example/ directory for our myexponent crate containing a file named basic.rs:

// myexponent/examples/basic.rs

use myexponent::pow;

fn main() {
println!("8 raised to 2 is {}", pow(8, 2));
}

Under the examples/ directory, we imported our pow function from our myexponent crate. The following is the output upon running cargo run --example basic: