Module 2Borrowing & ReferencesLesson 4 of 920 min
Immutable Borrows (&T)
Read data without taking ownership — the default for helpers and metrics.
Borrow with &
rust
fn mid(bid: &f64, ask: &f64) -> f64 {
(*bid + *ask) / 2.0
}
// or simply take f64 by Copy for numbers — but the idea matters for String/structFor non-Copy types:
rust
fn print_ticker(t: &String) {
println!("{t}");
}
// better API: fn print_ticker(t: &str)
fn main() {
let ticker = String::from("AAPL");
print_ticker(&ticker);
println!("still own: {ticker}");
}Output
AAPL
still own: AAPLMany readers OK
rust
fn main() {
let s = String::from("IBM");
let r1 = &s;
let r2 = &s;
println!("{r1} {r2}");
}Output
IBM IBMExercise
Compute mid and spread from a borrowed quote struct.
Challenge
Add fn is_locked(q: &Quote, max_spread: f64) -> bool.
Tips
- Field access through &Quote does not need explicit *
- Prefer &str over &String in APIs
- Borrowing keeps the owner valid
Try it live
Immutable Borrows (&T)Rust 2021
Loading editor…
Output
Press Run to compile and execute.