Part 01 · Rust Is Not Scary
Your First Rust Program
Create a project, read every line of the file cargo made for you, and run it.
⏱ 9 min · Station 4 of 75
The story
Opening a new shop takes two things before you sell anything: a signboard that says the shop's name, and a front door where customers come in. Every Rust project has the same two things. Cargo.toml is the signboard: the project's name, version, and the libraries it uses. fn main is the front door: the place where your program starts, every single time.
In this lesson you'll make a project for our shop, read every line cargo wrote for you, change it, and run it.
The idea
A Rust program is a project managed by cargo, not a loose file. You create one with cargo new:
cargo new shop-hello
cd shop-hello
Creating binary (application) `shop-hello` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
.
./Cargo.toml
./src
./src/main.rs
Two files, and both matter.
Cargo.toml, the signboard:
[package]
name = "shop-hello"
version = "0.1.0"
edition = "2024"
[dependencies]
[package]: this section describes the project itself.name: the project's name, and also the name of the program file you'll get.version: your project's version, written as major.minor.patch.edition = "2024": which edition of the Rust language to use. Editions come every few years and can change small details of the syntax; old editions keep working forever, so a project from 2018 still compiles today.[dependencies]: the libraries (cargo calls them crates) your project uses. Empty for now.
(Outside an existing git repository, cargo new also runs git init and writes a .gitignore that ignores target/. Ours was created inside one, so it skipped that.)
src/main.rs, the front door:
fn main() {
println!("Hello, world!");
}
fnstarts a function.mainis a special name: it is where every Rust program begins.()meansmaintakes no input.{ ... }is the function's body, the code that runs.println!prints a line of text. The!matters:println!is a macro, not a function. A macro is code that writes more code for you at compile time. Here it checks your text and your{}placeholders before the program runs."Hello, world!"is the text, inside double quotes.;ends the statement.
Try it: make it say something
Replace main.rs with this. Each {} is a hole that gets filled with the next value after the text:
fn main() {
println!("Welcome to Rahim Store!");
println!("Today we have {} items in stock.", 128);
println!("{} + {} = {}", 2, 3, 2 + 3);
}
What does the third line print?
cargo run
Compiling shop-hello v0.1.0 (/home/you/rust-lab/shop-hello)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.13s
Running `target/debug/shop-hello`
Welcome to Rahim Store!
Today we have 128 items in stock.
2 + 3 = 5
Three commands you will use all the time, and what each one does:
| Command | What it does | When to use it |
|---|---|---|
cargo check | checks the code, does not make a program | while writing; the fastest feedback |
cargo build | checks and builds the program into target/debug/ | when you want the file but not to run it |
cargo run | builds if something changed, then runs it | most of the time |
Checking shop-hello v0.1.0 (/home/you/rust-lab/shop-hello)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s
Compiling shop-hello v0.1.0 (/home/you/rust-lab/shop-hello)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
build
deps
examples
incremental
shop-hello
Welcome to Rahim Store!
Today we have 128 items in stock.
2 + 3 = 5
cargo check said Checking and finished in about a third of the build time (0.03 s against 0.09 s), because it stops before making machine code. In a big project that difference grows from milliseconds to many seconds, so cargo check (and rust-analyzer, which does the same in your editor) is what you lean on while writing.
What the compiler says
Everyone forgets the ! on their first day. Here's what happens:
fn main() {
println("Welcome to Rahim Store!");
}
error[E0423]: expected function, found macro `println`
--> src/main.rs:2:5
|
2 | println("Welcome to Rahim Store!");
| ^^^^^^^ not a function
|
help: use `!` to invoke the macro
|
2 | println!("Welcome to Rahim Store!");
| +
For more information about this error, try `rustc --explain E0423`.
error: could not compile `broken` (bin "broken") due to 1 previous error
Read it top to bottom:
error[E0423]: expected function, found macro `println`: you wrote it like a function call, butprintlnis a macro.--> src/main.rs:2:5: line 2, column 5.^^^^^^^ not a function: the arrows point at exactly the word that is wrong.help: use `!` to invoke the macro: the fix, shown as the corrected line. The+under it marks the one character to add.
The second-most common first-day error is a missing semicolon:
fn main() {
println!("Welcome to Rahim Store!")
println!("Today we have {} items in stock.", 128);
}
error: expected `;`, found `println`
--> src/main.rs:2:40
|
2 | println!("Welcome to Rahim Store!")
| ^ help: add `;` here
3 | println!("Today we have {} items in stock.", 128);
| ------- unexpected token
error: could not compile `b2` (bin "b2") due to 1 previous error
The compiler expected ; at the end of line 2 and found the next println instead. Again it says where (2:40, right after the closing parenthesis) and what to add (help: add `;` here).
Notice the pattern. Both errors say what is wrong, where, and how to fix it. You will see this shape a thousand times, and The Compiler Is Your Teacher takes it apart properly.
Under the hood
What actually happens between typing cargo run and seeing the output?
- cargo reads
Cargo.toml, sees which files changed since the last build, and decides whether anything needs compiling. (Nothing changed? It skips straight to step 4.) - rustc checks your code (types, borrowing, everything the later lessons cover) and turns it into machine code.
- The linker (
ccon Linux, the same one that failed in Set Up Rust when it was missing) joins your code with the system's C library into one program file. - The operating system starts that file:
target/debug/shop-hello.
That file is a normal program. You can copy it to another Linux machine with the same CPU type and run it there without Rust installed. That is very different from Python, where the machine needs Python itself to run your script.
Compared with other languages
The same two lines in Python and Go:
print("Welcome to Rahim Store!")
print("Today we have {} items in stock.".format(128))
package main
import "fmt"
func main() {
fmt.Println("Welcome to Rahim Store!")
fmt.Printf("Today we have %d items in stock.\n", 128)
}
Welcome to Rahim Store!
Today we have 128 items in stock.
| Python | Go | Rust | |
|---|---|---|---|
| Start point | top of the file | func main() | fn main() |
| Project file | none needed | go.mod | Cargo.toml |
| Print with values | print(...), .format | fmt.Printf("%d") | println!("{}") |
| Checks before running | almost none | types | types, ownership, borrowing |
| What you ship | the script + Python | one program file | one program file |
Go and Rust look alike here: both have a main function and both build one program file. The difference shows up later, in what the compiler checks.
Key takeaway
cargo new gives you a project with two important files: Cargo.toml (name, version, edition, libraries) and src/main.rs, where fn main is the front door every run starts from. println! is a macro, which is why it has a !, and its {} placeholders are checked at compile time. Use cargo check while writing, cargo run to try it. Every compiler error tells you what, where, and usually how to fix it.
Practice
Objective: use println! placeholders to print a neat table.
Challenge: print a small receipt for Rahim Store: a header row, three items with prices in taka, and a total that Rust adds up for you. Line the names up on the left and the prices on the right.
Expected result:
Item Taka
Rice 5kg 420
Soybean oil 185
Eggs (12) 150
Total 755
Hint 1
Make a new project with cargo new receipt, and write all your lines inside fn main.
Hint 2
Inside the braces you can give a width: {:<12} pads to 12 characters and keeps the text on the left; {:>8} pads to 8 and pushes it to the right.
Hint 3
For the total, put the sum straight in as a value: println!("{:<12}{:>8}", "Total", 420 + 185 + 150);.
Solution
fn main() {
println!("{:<12}{:>8}", "Item", "Taka");
println!("{:<12}{:>8}", "Rice 5kg", 420);
println!("{:<12}{:>8}", "Soybean oil", 185);
println!("{:<12}{:>8}", "Eggs (12)", 150);
println!("{:<12}{:>8}", "Total", 420 + 185 + 150);
}
Try changing {:>8} to {:<8} on one line and run it again to see the price jump to the left. Next lesson you'll keep these prices in variables instead of typing them twice.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →