Rs
Module 3Structs & MethodsLesson 1 of 920 min

Struct Basics

Define Order and Quote structs, construct them, and compute simple fields.

Why structs?

A pile of loose variables:

rust
let bid = 100.0;
let ask = 100.05;
let ticker = "AAPL";

…does not scale. A struct names the bundle and documents intent.

Define and construct

rust
fn main() {
    struct Quote {
        bid: f64,
        ask: f64,
    }

    let q = Quote { bid: 100.0, ask: 100.05 };
    println!("bid={}", q.bid);
    println!("ask={}", q.ask);
}
Output
bid=100
ask=100.05

Field init shorthand

If a variable name matches the field:

rust
let bid = 100.0;
let ask = 100.05;
let q = Quote { bid, ask };

Debug printing

rust
#[derive(Debug)]
struct Order { ticker: String, qty: i64, limit: f64 }

fn main() {
    let order = Order {
        ticker: "AAPL".into(),
        qty: 100,
        limit: 190.5,
    };
    println!("{:?}", order);
}
Output
Order { ticker: "AAPL", qty: 100, limit: 190.5 }

Walkthrough: order notional

Notional = quantity × price. With a struct, that formula lives next to the data (methods in the next lesson).

Common mistakes

  • Forgetting commas between fields
  • Moving a struct with String fields then using the old name
  • Using {} without Display — use {:?} with Debug

Try it

Challenge

Create a second order with struct update: Order { limit: 191.0, ..o } — you may need to clone ticker first.

Tips
  • #[derive(Debug)] enables {:?}
  • qty as f64 for float math
  • Structs make domain language explicit

Try it live

Struct BasicsRust 2021
Loading editor…
Output
Press Run to compile and execute.