Your First Rust Program
Prerequisites: Installing Rust
Rust projects are usually created and run with Cargo, Rust's build tool.
Syntax
cargo new hello
cd hello
cargo run
cargo new creates a project folder with this layout:
hello/
├── Cargo.toml
└── src/
└── main.rs
Cargo.toml describes the project. The edition line picks the
version of the language's rules to use — new projects get the latest,
2024:
[package]
name = "hello"
version = "0.1.0"
edition = "2024"
[dependencies]
Example
Cargo already wrote a program into src/main.rs:
fn main() {
println!("Hello, world!");
}
Run it from inside the hello folder with cargo run. Cargo first
prints a few status lines about compiling, then runs the program:
Compiling hello v0.1.0 (/home/ada/hello)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.52s
Running `target/debug/hello`
Expected output
Hello, world!
Line by line:
fn main()— declares a function namedmain. Every Rust program starts running here. It takes no arguments and returns nothing.{ ... }— the function body is wrapped in curly braces.println!(...)— prints text followed by a newline. The!meansprintln!is a macro, not a regular function. Macros generate code at compile time;println!uses that to check your format string while compiling. For now, just remember the!.;— ends the statement. Most lines of Rust end with a semicolon.
Common mistakes
- Forgetting the
!.println("Hello");fails with:
error[E0423]: expected function, found macro `println`
- Using single quotes for text. In Rust,
'a'is a single character; text needs double quotes.println!('Hello');fails with:
error: character literal may only contain one codepoint
- Running
cargo runoutside the project folder — Cargo reports "could not findCargo.toml".cdinto the folder first.
Practice
Change the program to print your own name on one line and your favorite programming language on the next.
Show solution
fn main() {
println!("Ada");
println!("Rust");
}