Skip to content

The basics

This section explains Rust from scratch, with examples you can copy into a console project and run with Ctrl/⌘+F5. You don’t need to know another language, although if you know C#, Java or Python you’ll recognize many things.

src/main.rs
fn main() {
println!("Hello, world!");
}
  • fn main() is the main function: the program starts here.
  • println! writes a line. The ! means it’s a macro (a kind of function that Rust expands at compile time); for now it’s enough to know that macros have a !.
  • Each statement ends with ;. Blocks go between { }.
fn main() {
let age = 30; // can't change
let mut points = 0; // mut: it can change
points += 10;
println!("Age {age}, points {points}");
}

In Rust variables are immutable by default: if you try to change age, the compiler warns you (and suggests adding mut). It feels awkward at first, but it prevents many bugs: when you read let you know that value doesn’t change later.

You can redeclare a variable with the same name (it’s called shadowing), useful to convert a value:

fn main() {
let text = "42";
let text: i32 = text.parse().unwrap(); // now it's a number
println!("{}", text + 1);
}

Rust infers the type almost always, but every value has one, and they don’t mix without converting:

Type What it holds Example
i32, i64 Signed integers -5, 1_000_000
u32, u64, usize Unsigned integers (usize: positions and sizes) 3, vec.len()
f64 Numbers with decimals 3.14
bool True or false true, false
char A single character (including accents and emoji) 'ñ', '✔'
String Text that can be modified and is yours String::from("hello")
&str A borrowed text (a “view” of a text) "hello"
fn main() {
let price: f64 = 9.99;
let quantity: i32 = 3;
let total = price * quantity as f64; // `as` converts between numbers
println!("Total: {total:.2}"); // :.2 → two decimals
}
fn area(width: f64, height: f64) -> f64 {
width * height // no `;`: it's the value it returns
}
fn greet(name: &str) {
println!("Hello, {name}!");
}
fn main() {
greet("Ann");
println!("Area: {}", area(3.0, 4.5));
}

Parameters always have a type, and -> type says what it returns. The last expression without ; is the return value (there’s also return, to leave early).

fn main() {
let grade = 6.5;
if grade >= 9.0 {
println!("Excellent");
} else if grade >= 6.0 {
println!("Passed");
} else {
println!("Failed");
}
// `if` is also an expression: it returns a value.
let status = if grade >= 6.0 { "passed" } else { "failed" };
println!("{status}");
}

The condition has to be a bool: if 1 { } doesn’t compile (in C it does).

fn main() {
// for: go through a range or a collection
for i in 1..=3 {
println!("Round {i}"); // 1, 2 and 3 (..= includes the end; .. doesn't)
}
// while: as long as a condition holds
let mut n = 10;
while n > 0 {
n -= 3;
}
// loop: forever, until a `break` (which can return a value)
let mut tries = 0;
let result = loop {
tries += 1;
if tries == 5 {
break tries * 2;
}
};
println!("n = {n}, result = {result}");
}
use std::io::{self, Write};
fn main() {
let name = "Ann";
let points = 7;
println!("{name} has {points} points"); // variables inside { }
println!("{} has {} points", name, points); // or in order
println!("[{:>5}] [{:<5}] [{:^5}]", 1, 2, 3); // align right, left, center
println!("{:?}", vec![1, 2, 3]); // {:?}: debug format
print!("Your number? ");
io::stdout().flush().unwrap(); // print! (without ln) isn't shown until you flush
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
let number: i32 = line.trim().parse().unwrap_or(0);
println!("Twice that is {}", number * 2);
}

In Raxorin Studio, type what the program asks for in the Input field of the Output panel.

Next: Ownership and borrowing, Rust’s most important idea.