Skip to content

Beginner · Getting started with Rust · topic 3 of 50 · 25 min

Your first program and cargo

Explanation

cargo new creates a project with a Cargo.toml file and src/main.rs. Every Rust program starts in fn main. println! prints a line; the exclamation mark means it is a macro. cargo run builds and runs, cargo check only checks for errors, and cargo build --release makes a fast, optimised program.

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.

bash
cargo new hello
cd hello
cargo run
Create a project called hello, go into it, and build and run it.

What cargo new creates

output
hello/
├── Cargo.toml      <- project name, version, edition, dependencies
├── .gitignore      <- tells git to ignore the target folder
└── src/
    └── main.rs     <- your code starts here
cargo also starts a git repository for you.
ini
[package]
name = "hello"
version = "0.1.0"
edition = "2024"

[dependencies]
Cargo.toml. The edition is a set of language rules; new projects use the 2024 edition.

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

rust
fn main() {
    println!("Hello, world!");
}
The program cargo new writes for you.
  • 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

rust
fn main() {
    let city = "Pune";
    let temp = 31;
    println!("{} is {} degrees today", city, temp);
    println!("{city} is {temp} degrees today");
    println!("{:?}", (city, temp));
}
Prints the same sentence twice, then ("Pune", 31). {} fills values in order; {name} uses a variable directly; {:?} is the debug format.

{} 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

CommandWhat it does
cargo runBuild (if needed) and run the program
cargo checkCheck for errors without making a program; much faster, great while writing code
cargo buildBuild a debug program in target/debug
cargo build --releaseBuild an optimised program in target/release: slower to compile, much faster to run
cargo fmtFormat your code in the standard style
cargo clippyRun the linter for extra warnings and tips
Careful: Never measure speed with a debug build. Debug builds skip optimisations so they compile fast; a release build can be ten times faster or more. Use cargo run --release when you time things.

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

cargo new hello cargo run

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.

rust
fn main() {
    let item = "Toor dal 1 kg";
    let price = 140;
    let qty = 2;
    println!("{item} x {qty} = Rs {}", price * qty);
}
Prints: Toor dal 1 kg x 2 = Rs 280

Practice (0/3 done)

Task 1 · Question

What does this program print? fn main() { let a = 4; let b = 5; println!("{a} + {b} = {}", a + b); }

Task 2 · Question

Which line does NOT compile?

Task 3 · Practice

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

Question 1

1.Where does a cargo project keep its main code?

Question 2

2.Which command checks your code for errors fastest, without producing a program?

Question 3

3.What is {:?} used for in println!?

Question 4

4.What is Cargo.toml?

Question 5

5.Why can a release build be much faster than a debug build?

Read more (free)

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.

From Packages, crates and modules

What does cargo-audit check?Related

Answer: Dependencies against a database of known vulnerabilities

It uses the RustSec advisory database.

From Tooling: rustfmt, Clippy, docs and editions

Which command shows println! output from passing tests?Related

Answer: cargo test -- --nocapture

--nocapture is passed to the test runner after --.

From Unit tests

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.

From Integration tests and doc tests

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. 1 more topic in “Getting started with Rust” before its exam: Variables, mutability, shadowing and constants.
  2. Module 1 exam: Getting started with Rust · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Types, control flow and functions. 50 topics left in the course before the final exam.

← Previous: Installing Rust with rustup