Cargo Basics
In this page:
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
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
[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
fn main() {
println!("Generated by cargo new");
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let reasons = ["dependency management", "consistent builds", "built-in testing"];
for r in reasons.iter() {
println!("Cargo handles: {}", r);
}
}
Login to try C/C++/Java/PHP code in the editor
- Writing Rust files by hand for anything beyond a single-file experiment instead of letting Cargo scaffold a project.
- Editing files inside the
target/directory, which is regenerated build output and gets overwritten. - Forgetting that project metadata and dependencies live in
Cargo.toml, not scattered across source files.
- Cargo is Rust's official build tool and package manager, installed automatically alongside rustc via rustup.
cargo new project_namescaffolds a new project with aCargo.tomlfile and asrc/main.rsstarter file.Cargo.tomlstores 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: