Hello World in Rust
Your first Rust program - the classic Hello World example with Docker setup
Every programming journey starts with Hello World. Let’s write our first Rust program.
The Code
Create a file named hello.rs:
| |
Understanding the Code
fn main()- The entry point of every Rust executable.fndeclares a function.println!- A macro (note the!) that prints to standard output with a newline. Macros are distinguished from functions by the exclamation mark."Hello, World!"- A string literal. Rust strings are UTF-8 encoded.
Running with Docker
The easiest way to run this without installing Rust locally:
| |
Running Locally
If you have Rust installed (via rustup):
| |
Or use Cargo (Rust’s build tool) for a proper project:
| |
Expected Output
Hello, World!
Key Concepts
- Rust is compiled - Source code (
.rs) is compiled directly to machine code, no VM needed main()is special - Every executable must have amainfunction as its entry point- Macros vs Functions -
println!is a macro; regular functions don’t have! - Semicolons matter - Statements end with semicolons; expressions don’t
- Cargo is preferred - While
rustcworks, real projects use Cargo for dependency management
Why println! Is a Macro
You might wonder why println! has that !. In Rust, macros can:
- Accept variable numbers of arguments
- Do compile-time string formatting
- Generate code at compile time
println! uses these capabilities to provide type-safe formatting without runtime overhead.
A Slightly More Complex Example
| |
This demonstrates:
let- Variable binding (immutable by default){}- Format placeholder (like%sin C or{}in Python)
Next Steps
Continue to Variables and Data Types to learn about Rust’s ownership system and how it handles data.
Running Today
Last updated: