← Back to Rust Course | Chapter 1: Setup & Basics | Lesson 4 of 7

Cargo Basics

Cargo is a helper that creates new Rust projects for you and keeps all their pieces organized.

Creating a New Project

cargo new scaffolds a complete, ready-to-build Rust project: it creates a project folder, a Cargo.toml manifest file, a src/ directory, and a starter src/main.rs file containing a 'Hello, world!' program.

Example: Creating a New Project

bash
cargo new hello_cargo

⚠️ Run this command in your terminal.

The Cargo.toml Manifest

Cargo.toml is the project's manifest file. It records the package name, version, Rust edition, and any external dependencies (crates) the project needs. Cargo reads this file to know how to build your project.

Example: The Cargo.toml Manifest

bash
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"

[dependencies]

⚠️ Run this command in your terminal.

The src Directory

Cargo expects your source code inside a src/ folder, with src/main.rs as the entry point for a binary program. Keeping this structure means every Cargo command knows exactly where to find your code without extra configuration.

Example: The src Directory

markup
fn main() {
    println!("Generated by cargo new");
}

Why Use Cargo Instead of rustc Directly

As soon as a project grows beyond one file or needs external libraries, calling rustc directly becomes tedious. Cargo automates compiling, dependency management, testing, and packaging with a handful of simple subcommands, which is why virtually all real Rust projects use it.

Example: Why Use Cargo Instead of rustc Directly

markup
fn main() {
    let reasons = ["dependency management", "consistent builds", "built-in testing"];
    for r in reasons.iter() {
        println!("Cargo handles: {}", r);
    }
}
Common Mistakes
  1. Writing Rust files by hand for anything beyond a single-file experiment instead of letting Cargo scaffold a project.
  2. Editing files inside the target/ directory, which is regenerated build output and gets overwritten.
  3. Forgetting that project metadata and dependencies live in Cargo.toml, not scattered across source files.
Chapter Summary
  • Cargo is Rust's official build tool and package manager, installed automatically alongside rustc via rustup.
  • cargo new project_name scaffolds a new project with a Cargo.toml file and a src/main.rs starter file.
  • Cargo.toml stores project metadata (name, version) and dependencies.
  • The target/ directory holds compiled build artifacts and should not be edited by hand.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.