How to Create a New Rust Project with Cargo

Use `cargo new` to initialize a new binary project or `cargo new --lib` for a library, then navigate into the directory to start coding.

Use cargo new to initialize a new binary project or cargo new --lib for a library, then navigate into the directory to start coding. Cargo automatically generates the standard project structure, including Cargo.toml for configuration and the src directory for your source code.

For a standard binary application named my_app, run the following command in your terminal:

cargo new my_app
cd my_app
cargo run

This creates a directory structure with Cargo.toml and src/main.rs. The cargo run command compiles the project and executes the default "Hello, world!" program immediately. If you need a library instead of a binary, add the --lib flag:

cargo new --lib my_library

This generates src/lib.rs instead of src/main.rs, allowing you to export functions for use by other crates. You can verify the project structure with tree or ls -R to see the generated files.

Once inside the project directory, use cargo build to compile without running, or cargo check for a faster syntax and type validation. If you need to add external dependencies, edit Cargo.toml manually or use cargo add <crate_name>. For example, to add the serde crate:

cargo add serde --features derive

This updates Cargo.toml and downloads the necessary crates from crates.io. The --features derive flag enables the derive macros needed for serialization. Always run cargo fmt to format your code according to Rust standards and cargo clippy to catch common mistakes before building.

If you encounter permission errors on Linux or macOS, ensure your user has write access to the target directory, though this is rare for new projects. On Windows, ensure you have the Rust toolchain installed via rustup before running these commands. The generated Cargo.toml file is the heart of your project; it defines the package name, version, and dependencies. You can customize the edition (e.g., edition = "2021") in this file to use the latest language features.

Remember that cargo manages the build artifacts in a hidden target directory, so you don't need to manually handle compilation flags or output paths. This setup ensures your project is reproducible and ready for collaboration or deployment immediately after creation.