Module 1Variables & TypesLesson 6 of 1020 min
Tuples & Arrays Intro
Fixed-size groups of values: quote pairs, OHLC bars, and small matrices of numbers.
Tuples — heterogeneous, fixed length
rust
let quote: (f64, f64) = (100.0, 100.05); // bid, ask
let (bid, ask) = quote; // destructure
let mid = (quote.0 + quote.1) / 2.0;Great for returning multiple values without a full struct yet.
Arrays — homogeneous, fixed length
rust
fn main() {
let closes: [f64; 5] = [10.0, 10.5, 10.25, 10.75, 11.0];
println!("first={} last={}", closes[0], closes[4]);
println!("len={}", closes.len());
}Output
first=10 last=11
len=5Arrays live on the stack (when small) and have size known at compile time.
When to use which
| Need | Prefer |
|---|---|
| bid+ask pair quickly | tuple or later struct Quote |
| 5 known scenario shocks | array [f64; 5] |
| Growing trade list | Vec (Module 4) |
Example: OHLC
rust
fn main() {
let bar: (f64, f64, f64, f64) = (100.0, 102.0, 99.5, 101.0);
let (o, h, l, c) = bar;
println!("range = {:.2}", h - l);
println!("ret = {:.4}", c / o - 1.0);
}Output
range = 2.50
ret = 0.0100Exercise
Store 4 closes in an array; print first/last and a simple return.
Challenge
Make an array of 3 (bid, ask) tuples and print the mid for each.
Tips
- Array type is [T; N] — length is part of the type
- Out-of-bounds index panics at runtime
- Destructuring makes tuple code readable
Try it live
Tuples & Arrays IntroRust 2021
Loading editor…
Output
Press Run to compile and execute.