Ch1. Getting started
Cargo Overview
- Cargo: Rust’s build system and package manager.
- Manages tasks like building code, downloading dependencies, and building libraries.
- Simplifies adding dependencies for more complex projects.
- Most Rust projects use Cargo, and the text assumes Cargo usage throughout.
Creating a Cargo Project
-
To create a new project:
cargo new hello_cargo cd hello_cargo- Creates a project directory with:
Cargo.toml: Configuration file in TOML format.src/main.rs: Contains the main program..gitignore: Initializes a Git repository (can be skipped with--vcsflag).
- Creates a project directory with:
Project Structure
- Cargo organizes files:
- Top-level directory: For configuration files like
Cargo.toml, README, and license information. srcdirectory: Holds the source code.
- Top-level directory: For configuration files like
- To convert a non-Cargo project, move the code to
srcand create aCargo.tomlfile.
Building and Running with Cargo
-
Build the project:
cargo build- Generates the executable in
target/debug. - To run:
./target/debug/hello_cargo- Cargo.lock: Tracks exact versions of dependencies.
- Generates the executable in
-
Run and build in one step:
cargo run -
Skips rebuild if no changes are detected.
Checking Code without Building
-
Use
cargo checkfor faster compile checks without generating an executable:cargo check
Building for Release
-
For optimized builds:
cargo build --release -
Produces a binary in
target/release. -
Optimizations improve runtime performance but increase compile time.
Last updated on