A Hello World is the minimum program that allows us to verify that everything works before diving into the thick of things.
It might seem trivial because it just prints text to the screen. But in reality, it helps us verify the compiler, Cargo, the project structure, and the execution of a Rust program.
Creating the Project
We’ll use cargo, as it’s the standard way to work in Rust. Let’s create a new project:
cargo new hello_rust
cd hello_rustCargo creates a folder that looks like this:
hello_rust/
├─ Cargo.toml
└─ src/
└─ main.rsThe important file right now is src/main.rs. That’s where our program lives.
The First main
If we open src/main.rs, we’ll see something like this:
fn main() {
println!("Hello, world!");
}And that’s it. With two lines, we have our first Rust program.
If you come from other languages, it might be surprising that there’s no Program class, no public static void main, or any other ceremony around it. Rust can be very strict, yes, but it doesn’t like adding noise just for the sake of it.
Running the Program
To compile and run, we use:
cargo runCargo will do two things:
It will compile the project.
It will execute the resulting binary.
The output will be something like:
Hello, world!The first time will take a bit longer because Cargo creates the target folder, where it stores binaries and intermediate files. Subsequent compilations are usually faster.
What Each Part Means
Let’s dissect the example, because several important things appear here.
fn main() {
println!("Hello, world!");
}fnstands for function. In Rust, functions are declared with the keywordfn.mainis the entry point of the program. When we run a binary, Rust looks for a function namedmainand starts there.- The curly braces
{ ... }delimit the function body. Everything inside them will be executed whenmainis called. println!prints text to the screen. That exclamation mark is not decorative: it meansprintln!is a macro, not a regular function.
The Semicolon
The line ends with ;. In Rust, the semicolon indicates that the line is a statement. For now, just remember that.
println!("Hello, world!");Later on, we’ll see that Rust makes a clear distinction between statements and expressions, and that this difference is more important than it seems.
Compiling Without Running
If we only want to check that the code compiles, we can use:
cargo checkcargo check does not generate the final binary, so it’s faster. You’ll use it a lot while writing code.
To compile in development mode without running:
cargo buildAnd for an optimized build:
cargo build --releaseThe release mode takes longer but produces a much more optimized binary.