hola-mundo-rust

Hello World in Rust: Structure of Your First Project

  • 3 min

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_rust
Copied!

Cargo creates a folder that looks like this:

hello_rust/
├─ Cargo.toml
└─ src/
   └─ main.rs
Copied!

The 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!");
}
Copied!

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 run
Copied!

Cargo will do two things:

It will compile the project.

It will execute the resulting binary.

The output will be something like:

Hello, world!
Copied!

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!");
}
Copied!
  • fn stands for function. In Rust, functions are declared with the keyword fn.
  • main is the entry point of the program. When we run a binary, Rust looks for a function named main and starts there.
  • The curly braces { ... } delimit the function body. Everything inside them will be executed when main is called.
  • println! prints text to the screen. That exclamation mark is not decorative: it means println! 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!");
Copied!

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 check
Copied!

cargo 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 build
Copied!

And for an optimized build:

cargo build --release
Copied!

The release mode takes longer but produces a much more optimized binary.