Module 1Functions & Control FlowLesson 7 of 1022 min
Functions & Return Values
Write reusable pricing helpers: parameters, returns, and expression-bodied functions.
Anatomy
rust
fn mid_price(bid: f64, ask: f64) -> f64 {
(bid + ask) / 2.0 // last expression = return value (no semicolon)
}- Parameters need types
- Return type after
-> return x;works for early exits; final value usually omitsreturn
Early return
rust
fn safe_div(a: f64, b: f64) -> f64 {
if b == 0.0 {
return 0.0;
}
a / b
}Multiple helpers
rust
fn notional(qty: f64, px: f64) -> f64 { qty * px }
fn fee(notional: f64, bps: f64) -> f64 { notional * bps / 10_000.0 }Exercise
Implement compound growth and a year-by-year reporter using a function.
Challenge
Write monthly_compound(p, annual_rate, years) using rate/12 and years*12 periods.
Tips
- No semicolon on the returned expression
- powi takes i32 for f64
- Functions take ownership of arguments unless you borrow (next modules)
Try it live
Functions & Return ValuesRust 2021
Loading editor…
Output
Press Run to compile and execute.