Module 3Structs & MethodsLesson 2 of 922 min
impl Methods & Associated Functions
Position::new, market_value, and unrealized PnL with &self.
impl blocks
rust
struct Position {
qty: f64,
avg_price: f64,
}
impl Position {
fn new(qty: f64, avg_price: f64) -> Self {
Self { qty, avg_price }
}
fn market_value(&self, mark: f64) -> f64 {
self.qty * mark
}
}
fn main() {
let pos = Position::new(100.0, 50.0);
println!("MV={:.2}", pos.market_value(53.25));
}Output
MV=5325.00Receiver types
| Receiver | Meaning |
|---|---|
&self |
read-only method |
&mut self |
may mutate |
self |
consumes the value |
Associated vs method
Position::new(...)— no instance yetpos.market_value(mark)— called on instance
Unrealized PnL
For a simple linear position:
uPnL = qty * (mark - avg_price)
(works for shorts if qty is signed)
Exercise
Challenge
Add is_long/is_flat and test a short position qty=-40, avg=50, mark=48.
Tips
- Self in impl means the struct type
- &self does not take ownership
- Keep formulas in methods for reuse
Try it live
impl Methods & Associated FunctionsRust 2021
Loading editor…
Output
Press Run to compile and execute.