Rust: reference

A language without a garbage collector: memory safety, ownership, traits and C++-level speed.

Program structure

Minimal program

Execution starts at the main function. println! is a macro (you can tell by the !) that prints a line and moves to a new one.

fn main() {
    println!("Hello, world!");
}

Cargo: build and run

cargo manages the project, dependencies and the build. Run the commands in a terminal; the code lives in src/main.rs.

cargo new hello          # create a project
cd hello
cargo run                # build and run
cargo build --release    # optimized build
rustc main.rs            # compile a single file

Variables and types

let, mut and const

Variables are immutable by default, mut allows changes. A repeated let creates a new variable (shadowing), and const requires a type.

let age = 16;
let mut score = 0;
score += 10;
let age = age + 1;
const MAX: u32 = 100;
println!("{age} {score} {MAX}");

Basic types

Signed integers are i8...i128, unsigned are u8...u128, floats are f32 and f64. char is a Unicode character. The type is usually inferred.

let i: i32 = -42;
let n: u64 = 7;
let f: f64 = 3.14;
let b: bool = true;
let c: char = 'z';
let t: (i32, &str) = (1, "one");
println!("{} {}", t.0, t.1);

Type conversion

There are no implicit conversions: as for numbers, parse to turn a string into a number, From and into for safe conversions.

let x: i32 = 7;
let y = x as f64 / 2.0;
let n: i32 = "12".parse().unwrap();
let s = n.to_string();
let big = i64::from(x);
println!("{y} {n} {s} {big}");

Strings

String and &str

&str is a reference to text, String owns its data and can grow. len counts bytes, while chars().count() counts characters.

let s: &str = "hello";
let mut owned = String::from("Hello");
owned.push_str(", world");
owned.push('!');
println!("{owned} {} {}", owned.len(), owned.chars().count());

Formatting

println! and format! insert values into {}. {:.2} sets the decimal places, {:?} prints a value for debugging.

let name = "Alex";
let age = 16;
println!("{name} is {age} years old");
println!("{:.2} {:>5} {:?}", 3.14159, 42, "text");
let line = format!("{}-{}", name, age);

String methods

The methods trim, replace, split, contains do not change the original, they return a new string or iterator.

let s = "  Hello, Rust  ";
let t = s.trim();
println!("{}", t.to_uppercase());
println!("{}", t.replace("Rust", "world"));
println!("{:?}", t.split(", ").collect::<Vec<_>>());
println!("{}", t.contains("Rust"));

Conditions

if as an expression

Parentheses around the condition are not needed, but the condition itself must be a bool. if is an expression, so it returns a value.

let n = 7;
if n % 2 == 0 {
    println!("even");
} else if n > 5 {
    println!("odd and greater 5");
} else {
    println!("odd");
}
let kind = if n < 0 { "minus" } else { "plus" };

match

match must cover every case, otherwise the compiler reports an error. _ catches the rest, ..= is an inclusive range, | means "or".

let day = 6;
match day {
    1..=5 => println!("weekday"),
    6 | 7 => println!("weekend"),
    _ => println!("no such day"),
}

if let and let else

if let unpacks a single pattern without a full match. let ... else leaves the function if the pattern does not match.

let maybe: Option<i32> = Some(3);
if let Some(x) = maybe {
    println!("got {x}");
}
let Some(y) = maybe else { return };
println!("{y}");

Loops

loop, while, for

loop runs forever until a break. 0..3 is a range without its end (0, 1, 2), while 0..=3 includes 3.

let mut n = 0;
loop {
    n += 1;
    if n == 3 { break; }
}
while n > 0 { n -= 1; }
for i in 0..3 {
    println!("{i}");
}

Iterating and continue

enumerate adds the element number. loop is also an expression: the value after break becomes the result of the loop.

for i in 1..=5 {
    if i % 2 == 0 { continue; }
    println!("{i}");
}
for (i, ch) in "Rust".chars().enumerate() {
    println!("{i} {ch}");
}
let v = loop { break 42; };

Functions

Declaration

Parameter and return types are required. The last expression without ; becomes the function value, return is for early exit.

fn add(a: i32, b: i32) -> i32 {
    a + b
}
fn greet(name: &str) {
    println!("Hello, {name}!");
}
println!("{}", add(2, 3));
greet("Alex");

Closures

Closures |x| ... capture variables from their surroundings. To move ownership into a closure, put move before it.

let factor = 3;
let triple = |x: i32| x * factor;
println!("{}", triple(5));
let mut count = 0;
let mut inc = || count += 1;
inc();
inc();
println!("{count}");

Multiple values

To return several values, use a tuple (A, B), then unpack it with let (a, b) = ....

fn min_max(v: &[i32]) -> (i32, i32) {
    (*v.iter().min().unwrap(), *v.iter().max().unwrap())
}
let (lo, hi) = min_max(&[3, 1, 4]);
println!("{lo} {hi}");

Ownership and borrowing

Ownership and moves

A value has one owner. Assigning a String moves it (a becomes unusable), clone makes a copy, simple types are copied automatically.

let a = String::from("text");
let b = a;
let c = b.clone();
println!("{b} {c}");
let n = 5;
let m = n;
println!("{n} {m}");

References and borrowing

& borrows a value read-only, &mut for changing it. At any time there are either many & or a single &mut.

fn len(s: &String) -> usize { s.len() }
fn shout(s: &mut String) { s.push('!'); }
let mut text = String::from("Hello");
println!("{}", len(&text));
shout(&mut text);
println!("{text}");

Lifetimes

The annotation 'a tells the compiler the result lives no longer than both arguments. Most lifetimes are inferred automatically.

fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}
println!("{}", longest("ab", "abc"));

Collections

Vec

Vec<T> is a dynamic array. v[i] panics out of bounds, while get returns an Option.

let mut v = vec![1, 2, 3];
v.push(4);
v[0] = 10;
println!("{:?} {}", v, v.len());
println!("{:?}", v.get(9));
println!("{:?}", v.pop());

Array, slice and tuple

An array [T; N] has a fixed length, a slice &[T] is a window onto part of it. A tuple groups values of different types.

let arr = [1, 2, 3];
let zeros = [0; 5];
let slice = &arr[1..];
let (x, y) = (1, 2.5);
println!("{} {:?} {:?} {x} {y}", arr.len(), zeros, slice);

HashMap

HashMap stores key-value pairs. entry().or_insert() adds a value if the key is missing. Iteration order is not guaranteed.

use std::collections::HashMap;
let mut ages = HashMap::new();
ages.insert("Amy", 16);
ages.insert("Ivan", 17);
*ages.entry("Amy").or_insert(0) += 1;
println!("{:?}", ages.get("Amy"));
println!("{}", ages.contains_key("Peter"));

Structs and enums

struct and impl

Methods are written in an impl block. The first parameter &self borrows the instance, Self stands for the type itself.

struct Point { x: i32, y: i32 }
impl Point {
    fn new(x: i32, y: i32) -> Self { Point { x, y } }
    fn dist2(&self) -> i32 { self.x * self.x + self.y * self.y }
}
let p = Point::new(3, 4);
println!("{}", p.dist2());

derive

derive automatically adds trait implementations: Debug for {:?} output, Clone for copies, PartialEq for ==.

#[derive(Debug, Clone, PartialEq)]
struct User { name: String, age: u8 }
let u = User { name: "Alex".to_string(), age: 16 };
let u2 = User { age: 17, ..u.clone() };
println!("{:?} {}", u2, u == u2);

enum with data

enum variants can carry data of different shapes. match extracts it and forces you to handle every variant.

enum Shape { Circle(f64), Rect { w: f64, h: f64 } }
fn area(s: &Shape) -> f64 {
    match s {
        Shape::Circle(r) => 3.14 * r * r,
        Shape::Rect { w, h } => w * h,
    }
}
println!("{}", area(&Shape::Rect { w: 2.0, h: 3.0 }));

Traits

trait and impl

A trait describes a set of methods, like an interface. A method can have a default implementation that a type may override.

trait Speak {
    fn name(&self) -> String;
    fn hello(&self) -> String { format!("I am {}", self.name()) }
}
struct Dog;
impl Speak for Dog {
    fn name(&self) -> String { "dog".to_string() }
}
println!("{}", Dog.hello());

Generics and bounds

T: PartialOrd + Copy restricts a generic type with traits. impl Trait in a parameter is a short form of such a bound.

fn largest<T: PartialOrd + Copy>(v: &[T]) -> T {
    let mut m = v[0];
    for &x in v { if x > m { m = x; } }
    m
}
fn show(x: impl std::fmt::Display) { println!("{x}"); }
println!("{}", largest(&[3, 9, 2]));
show(3.5);

dyn Trait

Box<dyn Trait> stores values of different types behind a shared trait, and the concrete method is chosen at run time.

use std::fmt::Display;
let items: Vec<Box<dyn Display>> = vec![Box::new(1), Box::new("two"), Box::new(3.5)];
for it in &items {
    println!("{it}");
}

Iterators

map, filter, collect

The adapters filter and map are lazy: they work only when collect or another consumer gathers the result.

let v = vec![1, 2, 3, 4, 5, 6];
let sq: Vec<i32> = v.iter()
    .filter(|&&x| x % 2 == 0)
    .map(|x| x * x)
    .collect();
println!("{:?}", sq);

sum, max, fold

The consumers sum, max, all, find, fold walk through the elements and return a single result.

let v = [3, 8, 1];
let total: i32 = v.iter().sum();
let max = v.iter().max();
let all_pos = v.iter().all(|&x| x > 0);
let first_big = v.iter().find(|&&x| x > 5);
let prod = v.iter().fold(1, |acc, x| acc * x);
println!("{total} {max:?} {all_pos} {first_big:?} {prod}");

zip, enumerate, rev

zip joins two sequences into pairs, enumerate adds an index, rev reverses the order.

let names = ["Amy", "Ivan"];
let ages = [16, 17];
for (n, a) in names.iter().zip(ages.iter()) {
    println!("{n}: {a}");
}
for (i, x) in names.iter().enumerate().rev() {
    println!("{i} {x}");
}

Error handling

Option

Option<T> is Some(value) or None. This is how Rust expresses a missing value instead of null.

fn find(v: &[i32], x: i32) -> Option<usize> {
    v.iter().position(|&a| a == x)
}
match find(&[5, 6, 7], 6) {
    Some(i) => println!("index {i}"),
    None => println!("none"),
}
println!("{}", find(&[1], 9).unwrap_or(0));

Result and ?

Result<T, E> is Ok or Err. The ? operator returns the error from the function at once and unwraps the value on success.

use std::num::ParseIntError;
fn double(s: &str) -> Result<i32, ParseIntError> {
    let n: i32 = s.trim().parse()?;
    Ok(n * 2)
}
println!("{:?}", double("21"));
match double("abc") {
    Ok(v) => println!("{v}"),
    Err(e) => println!("error: {e}"),
}

Option and Result methods

unwrap_or gives a fallback value, map_err changes the error type. unwrap and expect panic, so keep them for examples and tests.

let x: Option<i32> = Some(4);
println!("{:?}", x.map(|n| n * 2));
println!("{}", x.unwrap_or(0));
let r: Result<i32, String> = "7".parse::<i32>().map_err(|e| e.to_string());
println!("{:?} {}", r, r.is_ok());
let n: i32 = "5".parse().expect("not a number");

main returning Result

main can return a Result. Then ? works inside it too, and Box<dyn Error> accepts an error of any type.

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let n: i32 = "42".parse()?;
    println!("{n}");
    Ok(())
}

Modules and crates

mod and pub

Everything in a module is private by default, pub makes an item public. use shortens the path to it.

mod geometry {
    pub fn area(w: f64, h: f64) -> f64 { w * h }
    pub mod shapes {
        pub struct Square(pub f64);
    }
    fn hidden() {}
}
use geometry::shapes::Square;
println!("{} {}", geometry::area(2.0, 3.0), Square(2.0).0);

Modules in files

The line mod utils; includes the module from the utils.rs or utils/mod.rs file next to it.

// src/main.rs
mod utils;
use utils::helper;

// src/utils.rs
pub fn helper() {}

Dependencies in Cargo.toml

External libraries (crates) are listed in Cargo.toml, and cargo downloads them from crates.io during the build.

[dependencies]
serde = "1"
rand = "0.8"

# or with the command:
# cargo add rand

What is next

A lessons course for this language is on the way, and the reference is already available.

A course is on the way. For now only the reference is available; lessons and tasks will follow.