A note from Omer
Hello, Rust
A tiny first Rust program, how to run it, and what each part actually does.
Every language has to start somewhere.
For Rust, that somewhere is still the classic:
fn main() {
println!("Hello, world!");
}
It is only two lines of actual code, but there are already a few Rust ideas hiding inside it.
Getting Rust
The usual way to install Rust is with rustup.
On macOS or Linux:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
After the installer finishes, check that Rust is available:
rustc --version
You should get a Rust version back.
The smallest Rust program
Create a file called main.rs:
fn main() {
println!("Hello, world!");
}
fn defines a function, and main is the function Rust runs when the program
starts.
Then there is this:
println!("Hello, world!");
println! prints a line to the terminal.
The ! is not decoration. It tells us that println! is a Rust macro rather
than a normal function.
Compile it
Rust is compiled, so the source file first needs to become an executable:
rustc main.rs
On macOS or Linux, run it with:
./main
And there it is:
Hello, world!
That is a complete Rust program.
Using Cargo
Compiling a single file with rustc is useful for seeing what is happening, but
most Rust projects use Cargo.
Cargo is Rust’s build tool and package manager.
Create a new project:
cargo new hello-rust
cd hello-rust
Cargo creates a small project structure for you:
hello-rust/
├── Cargo.toml
└── src/
└── main.rs
Open src/main.rs and you will find something familiar:
fn main() {
println!("Hello, world!");
}
Now run it with:
cargo run
Cargo handles compiling the project and then starts the executable.
Change something
A first program is more useful once it stops being exactly the same as everyone else’s.
Try:
fn main() {
println!("Hello from Rust.");
println!("It works.");
}
Then run:
cargo run
That is basically the Rust development loop:
Change the code, compile it, run it, break something, and learn why.
From here, the interesting parts start: variables, types, functions, structs, enums, pattern matching, and eventually Rust’s ownership system.
But first: it compiles.