How to Run Specific Examples in a Cargo Project

Use the `cargo run --example <name>` command to execute a specific example file located in your project's `examples` directory.

Use the cargo run --example <name> command to execute a specific example file located in your project's examples directory. You can also pass arguments to the example by appending them after --, which separates Cargo flags from the program's own arguments.

Here is the basic syntax to run an example named hello_world:

cargo run --example hello_world

If your example accepts command-line arguments, use -- to pass them through to the binary:

cargo run --example hello_world -- --count 5 --verbose

This approach is particularly useful when you have multiple examples in your project and want to test a specific use case without building the entire workspace or running the main binary. Cargo automatically compiles the example as a separate binary target, linking it against your library code if one exists.

For more complex scenarios, such as running an example with a specific feature flag enabled, you can combine the --features flag:

cargo run --example advanced_query --features "async-support"

If you need to run an example in release mode for performance testing, add the --release flag before the --example flag:

cargo run --release --example benchmark

Remember that example files must be placed in the examples directory at the root of your crate. Cargo will automatically detect any .rs files in this directory and treat them as runnable examples. If you have a workspace, you can specify the package name using the -p flag to ensure you are running the example from the correct crate:

cargo run -p my-crate --example specific_example

This method is the standard way to validate library usage patterns, test specific functionality in isolation, or demonstrate API usage to other developers without modifying your main application logic.