What are examples and what are they used for?

Viewed 104

The directory layout of a Rust project should look like this (source)

.
├── Cargo.lock
├── Cargo.toml
├── benches
│   └── large-input.rs
├── examples
│   └── simple.rs
├── src
│   ├── bin
│   │   └── another_executable.rs
│   ├── lib.rs
│   └── main.rs
└── tests
    └── some-integration-tests.rs

What is the file simple.rs under examples? How do I execute it? How should the file look like?

1 Answers

Examples are useful in library crates to show how the crate is used.

An example can be an executable with a main method or a library; it can either be in a single file examples/example-name.rs or consist of several files in a subdirectory examples/example-name/, with the main method in main.rs. To compile a library example you need to specify its crate type in Cargo.toml:

[[example]]
name = "example-name"
crate-type = ["lib"]

Examples are compiled by cargo test to ensure that they are up to date with the crate. You can run a specific executable example by

cargo run --example <example-name>

and selectively build any example with

cargo build --example <example-name>

This is documented in the Cargo Reference.

Related