Structs, enums and match
Structs
Section titled “Structs”A struct groups related data, like a class without inheritance:
struct Product { name: String, price: f64, stock: u32,}
fn main() { let mut bread = Product { name: String::from("Bread"), price: 1.5, stock: 20 }; bread.stock -= 1; println!("{}: {} in stock", bread.name, bread.stock);}Methods with impl
Section titled “Methods with impl”A type’s functions go in an impl block:
struct Rectangle { width: f64, height: f64,}
impl Rectangle { /// An "associated function" (no self): used to create. It's called with Rectangle::square(3.0). fn square(side: f64) -> Self { Rectangle { width: side, height: side } }
/// &self: a method that reads the rectangle. fn area(&self) -> f64 { self.width * self.height }
/// &mut self: a method that modifies it. fn grow(&mut self, factor: f64) { self.width *= factor; self.height *= factor; }}
fn main() { let mut r = Rectangle::square(3.0); r.grow(2.0); println!("Area: {}", r.area()); // 36}&self, &mut self and self are the ownership rules applied to the object itself:
reading it, modifying it or consuming it.
Printing a struct: derive
Section titled “Printing a struct: derive”#[derive(Debug, Clone, PartialEq)]struct Point { x: i32, y: i32,}
fn main() { let a = Point { x: 1, y: 2 }; let b = a.clone(); println!("{a:?}"); // Point { x: 1, y: 2 } println!("{}", a == b); // true}#[derive(...)] asks the compiler to write the code for common things for you: Debug (printing with {:?}),
Clone (.clone()), PartialEq (comparing with ==), Default (a default value)…
An enum is a type that can be one of several options. Unlike other languages, each option can carry its own
data:
enum Shape { Circle(f64), // the radius Rectangle { width: f64, height: f64 }, Point, // no data}
fn area(s: &Shape) -> f64 { match s { Shape::Circle(r) => 3.14159 * r * r, Shape::Rectangle { width, height } => width * height, Shape::Point => 0.0, }}
fn main() { let shapes = [Shape::Circle(1.0), Shape::Rectangle { width: 2.0, height: 3.0 }, Shape::Point]; for s in &shapes { println!("{:.2}", area(s)); }}match compares a value against several patterns and runs the first one that matches. It has to cover every
case: if you add Shape::Triangle to the enum and forget to handle it, the program doesn’t compile and the error
tells you exactly which match needs updating.
fn describe(n: i32) -> &'static str { match n { 0 => "zero", 1 | 2 | 3 => "a few", // several options 4..=9 => "several", // a range x if x < 0 => "negative", // a condition (guard) _ => "many", // _: anything else }}
fn main() { for n in [0, 2, 7, -1, 50] { println!("{n}: {}", describe(n)); }}Option: a value that may be missing
Section titled “Option: a value that may be missing”Rust has no null. When something can be missing, Option is used, an enum from the standard library:
enum Option<T> { Some(T), // there's a value None, // there isn't}fn find(names: &[&str], wanted: &str) -> Option<usize> { for (i, n) in names.iter().enumerate() { if *n == wanted { return Some(i); } } None}
fn main() { let names = ["Ann", "Luis", "Eva"]; match find(&names, "Luis") { Some(i) => println!("It's at position {i}"), None => println!("It isn't there"), } // Shortcuts: if let Some(i) = find(&names, "Eva") { println!("Eva is at {i}"); } let pos = find(&names, "Zoe").unwrap_or(0); // default value if it's None println!("{pos}");}Since the type is Option<usize> and not usize, the compiler doesn’t let you forget the case where there’s no
value: the famous “null reference” error doesn’t exist in Rust.
Practice
Section titled “Practice”- Calculator: an
enum Operacionand astruct Calculadorawith methods andmatch. - Game of Life: a
struct Mundowithimpl.
Next: Errors: Result and ?.