Skip to content

Collections, iterators and traits

fn main() {
let mut grades = vec![6.5, 4.0, 7.0]; // vec!: create with values
grades.push(5.5); // add at the end
println!("There are {} grades", grades.len());
println!("The first is {}", grades[0]); // panics if it doesn't exist
if let Some(n) = grades.get(10) { // get: Option, no panic
println!("{n}");
}
for n in &grades { // iterate by borrowing (&)
println!("{n}");
}
grades.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{grades:?}");
}

Arrays ([1, 2, 3]) have a fixed size; Vec can grow. A &[T] (slice) is a borrow of part of either one, and it’s what functions usually take.

use std::collections::HashMap;
fn main() {
let mut ages: HashMap<String, u32> = HashMap::new();
ages.insert("Ann".to_string(), 30);
ages.insert("Luis".to_string(), 25);
if let Some(a) = ages.get("Ann") {
println!("Ann is {a}");
}
// entry: insert if it doesn't exist, and modify
let mut counts = HashMap::new();
for word in "a b a c a".split(' ') {
*counts.entry(word).or_insert(0) += 1;
}
println!("{counts:?}"); // {"a": 3, "b": 1, "c": 1} (in any order)
}

If you need the keys in order, use BTreeMap (same usage). The Word counter sample uses HashMap and entry.

A closure is a function without a name, written in place: |x| x * 2. Iterators chain operations on collections without writing loops:

fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let even_squares: Vec<i32> = numbers
.iter()
.filter(|n| *n % 2 == 0) // only the even ones
.map(|n| n * n) // square them
.collect(); // gather into a Vec
println!("{even_squares:?}"); // [4, 16, 36]
let sum: i32 = numbers.iter().sum();
let any_big = numbers.iter().any(|n| *n > 5);
let max = numbers.iter().max(); // Option<&i32>
println!("{sum} {any_big} {max:?}");
for (i, n) in numbers.iter().enumerate() { // with its position
if i < 2 {
println!("{i}: {n}");
}
}
}

Iterators aren’t slower than a hand-written for: the compiler turns them into the same code.

A trait defines methods that several types can implement, like a C# or Java interface:

trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String { // method with a default implementation
String::from("shape")
}
}
struct Circle { radius: f64 }
struct Square { side: f64 }
impl Shape for Circle {
fn area(&self) -> f64 { 3.14159 * self.radius * self.radius }
fn name(&self) -> String { String::from("circle") }
}
impl Shape for Square {
fn area(&self) -> f64 { self.side * self.side }
}
// Generic: accepts any type that implements Shape.
fn describe(s: &impl Shape) {
println!("{} with area {:.2}", s.name(), s.area());
}
fn main() {
describe(&Circle { radius: 1.0 });
describe(&Square { side: 2.0 });
// A list of shapes of different types: Box<dyn Shape>
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle { radius: 2.0 }), Box::new(Square { side: 3.0 })];
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("Total area: {total:.2}");
}

Many things in Rust are standard library traits: Display (how it’s printed with {}), Debug ({:?}), Clone, PartialEq (==), Iterator… Implementing them for your types makes them work with everything that already exists. The Geometry sample is built around a trait.

When a file grows, split it into modules:

src/main.rs
mod geometry; // looks for src/geometry.rs
use geometry::circle_area;
fn main() {
println!("{}", circle_area(1.0));
}
src/geometry.rs
pub fn circle_area(radius: f64) -> f64 {
std::f64::consts::PI * radius * radius
}

Everything is private by default; pub makes it visible outside the module. To share code between programs, create a library and add it as a reference (see Solutions and the Shop sample).