Skip to Content
RustBooksThe Rust BookCh1. Getting started

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 --vcs flag).

Project Structure

  • Cargo organizes files:
    • Top-level directory: For configuration files like Cargo.toml, README, and license information.
    • src directory: Holds the source code.
  • To convert a non-Cargo project, move the code to src and create a Cargo.toml file.

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.
  • Run and build in one step:

    cargo run
  • Skips rebuild if no changes are detected.

Checking Code without Building

  • Use cargo check for 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