rsRustPrimer
< Back to module

Structs, enums and pattern matching

Structs

A struct groups several named values into a single type, like a Java class without inheritance, or a Kotlin data class. You declare the fields and their types, then create an instance by giving every field a value.

rust
#[derive(Debug)]
struct Quote {
ticker: String,
bid: f64,
ask: f64,
}
fn main() {
let quote = Quote {
ticker: String::from("AIR.PA"),
bid: 151.20,
ask: 151.30,
};
println!("{} : {} / {}", quote.ticker, quote.bid, quote.ask);
println!("{quote:?}");
}
#[derive(Debug)] generates the debug formatting used by {:?}. Without it, println! refuses to print the struct.

Mutability applies to the whole instance: either the variable is mut and every field can change, or none can. Two handy shortcuts: if a variable has the same name as a field you write it once; and ..other copies the remaining fields from another instance.

rust
#[derive(Debug)]
struct Quote {
ticker: String,
bid: f64,
ask: f64,
}
fn main() {
let ticker = String::from("AIR.PA");
let mut quote = Quote { ticker, bid: 151.20, ask: 151.30 };
quote.bid = 151.25;
let wider = Quote { ask: 151.60, ..quote };
println!("{wider:?}");
}
Careful: ..quote moves the ticker String into wider. After that line quote.ticker can no longer be used (but quote.bid still can, f64 being Copy).

Tuple structs have unnamed fields. Their most common use is the newtype: wrapping an existing type to give it business meaning. A Notional(f64) and a Rate(f64) can no longer be mixed up, whereas two bare f64 values can.

rust
struct Notional(f64);
struct Rate(f64);
fn annual_interest(notional: Notional, rate: Rate) -> f64 {
notional.0 * rate.0
}
fn main() {
let interest = annual_interest(Notional(1_000_000.0), Rate(0.035));
// annual_interest(Rate(0.035), Notional(1_000_000.0)); // erreur : types inversés
println!("{interest}");
}

Your turn

Declare a Trade struct with an id (u32), a counterparty (String) and a notional (f64), then create an instance and print it with {:?}.

src/main.rs
// déclare la struct ici
fn main() {
// crée un Trade et affiche-le
}