Beginner · Getting started with Rust · topic 3 of 50 · 25 min
Your first program and cargo
Explanation
Why cargo?
You could compile a single file with rustc main.rs, but real programs have many files and use libraries written by others. cargo handles all of that: it creates the project, downloads libraries, compiles everything in the right order and runs your tests. Almost every Rust project uses cargo.
cargo new hello
cd hello
cargo runWhat cargo new creates
hello/
├── Cargo.toml <- project name, version, edition, dependencies
├── .gitignore <- tells git to ignore the target folder
└── src/
└── main.rs <- your code starts here[package]
name = "hello"
version = "0.1.0"
edition = "2024"
[dependencies]Cargo.toml is written in TOML, a simple settings format. The [dependencies] section lists libraries your project uses. In Rust, a library you can download is called a crate. After your first build, cargo also writes Cargo.lock (the exact versions it used) and a target folder (the compiled output).
Reading main.rs line by line
fn main() {
println!("Hello, world!");
}- fn main() defines a function named main. Every Rust program starts running here.
- The curly braces { } hold the body of the function.
- println! prints text and then a new line. The ! means println! is a macro, not a normal function. A macro is code that writes more code for you at compile time; println! uses this to check your placeholders.
- The line ends with a semicolon ;.
Printing values with placeholders
fn main() {
let city = "Pune";
let temp = 31;
println!("{} is {} degrees today", city, temp);
println!("{city} is {temp} degrees today");
println!("{:?}", (city, temp));
}{} uses the Display format, meant for users. {:?} uses the Debug format, meant for programmers; it works for things like lists and tuples that have no Display format. If you pass the wrong number of values, the program does not compile; the println! macro checks this for you.
The cargo commands you will use every day
| Command | What it does |
|---|---|
| cargo run | Build (if needed) and run the program |
| cargo check | Check for errors without making a program; much faster, great while writing code |
| cargo build | Build a debug program in target/debug |
| cargo build --release | Build an optimised program in target/release: slower to compile, much faster to run |
| cargo fmt | Format your code in the standard style |
| cargo clippy | Run the linter for extra warnings and tips |
Common mistakes
- Writing println("Hi") without the !. The error says println is a macro, so add the !.
- Using single quotes for text: 'Hello'. In Rust, single quotes are for one character (a char). Text uses double quotes.
- Forgetting a placeholder: println!("Total", total) does not compile. Write println!("Total {}", total).
- Committing the target folder to git. cargo's .gitignore already excludes it; keep it that way.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Your first program and cargo · 1/7
Time for your first Rust program. We will use cargo, Rust's build tool.
Prefer a video by a teacher? Find free videos on “rust cargo new hello world tutorial beginners” on YouTube ↗
In real life: A tiny tool for the shop counter
A kirana shop owner's nephew writes his first Rust program to print a bill line. He creates it with cargo new bill, edits main.rs, and runs it with cargo run. When it works, he builds a release version and copies target/release/bill.exe to the shop computer. That one file runs on its own: no Rust installation is needed on the shop computer.
fn main() {
let item = "Toor dal 1 kg";
let price = 140;
let qty = 2;
println!("{item} x {qty} = Rs {}", price * qty);
}Practice (0/3 done)
What does this program print? fn main() { let a = 4; let b = 5; println!("{a} + {b} = {}", a + b); }
Which line does NOT compile?
Create a project called intro with cargo new. Make it print your name, your city and your age, using {} placeholders and at least one {name} style placeholder. Run it with cargo run, then build a release version.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Variables, mutability, shadowing and constantsGetting started with Rust · same module
- Packages, crates and modulesModules, crates, traits and generics
- Tooling: rustfmt, Clippy, docs and editionsTesting, tooling and unsafe Rust
- Unit testsTesting, tooling and unsafe Rust
- Integration tests and doc testsTesting, tooling and unsafe Rust
- Building a CLI toolReal projects: CLI, web and WebAssembly
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Where does a cargo project keep its main code?
Answer: src/main.rs
cargo new puts the starting code in src/main.rs.
Which command checks your code for errors fastest, without producing a program?
Answer: cargo check
cargo check skips making the final program, so it is the fastest way to see errors.
What is {:?} used for in println!?
Answer: Printing in the Debug format, for programmers
{:?} uses the Debug format, which works for tuples, arrays and many other types.
What is Cargo.toml?
Answer: The project settings: name, version, edition and dependencies
Cargo.toml describes the project and lists the crates it depends on.
Why can a release build be much faster than a debug build?
Answer: The compiler applies optimisations
Release builds turn on optimisations; debug builds skip them to compile faster.
Why commit Cargo.lock for an application?Related
Answer: It pins exact dependency versions so builds are repeatable
Cargo.lock records the exact versions used.
What does cargo-audit check?Related
Answer: Dependencies against a database of known vulnerabilities
It uses the RustSec advisory database.
Which command shows println! output from passing tests?Related
What happens to code blocks inside /// comments when you run cargo test?Related
Answer: They are compiled and run as tests
Doc tests keep examples correct.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Getting started with Rust” before its exam: Variables, mutability, shadowing and constants.
- Module 1 exam: Getting started with Rust · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Types, control flow and functions. 50 topics left in the course before the final exam.