rsRustPrimer
< Back to module

Language basics

Functions and expressions

A function is declared with fn. Parameter types are mandatory, and so is the return type after ->. No inference at function boundaries: the signature is a contract you can read without looking at the body.

rust
fn discount_factor(rate: f64, years: f64) -> f64 {
(-rate * years).exp()
}
fn main() {
let df = discount_factor(0.03, 5.0);
println!("DF(5 ans) = {df:.4}");
}
{df:.4} prints 4 decimals. No return: the last expression is the returned value.

This is the key point: in Rust almost everything is an expression that produces a value, including a block between braces. Adding a semicolon turns an expression into a statement, which returns nothing (the unit type ()).

rust
fn square(x: f64) -> f64 {
x * x; // erreur : mismatched types, expected f64, found ()
}
The most common beginner mistake. The compiler suggests removing the semicolon.

Your turn

Write the forward_value function that returns the value of a long forward: (spot price minus agreed price) times quantity.

src/main.rs
fn forward_value(spot: f64, strike: f64, quantity: f64) -> f64 {
todo!()
}
fn main() {
println!("{}", forward_value(105.0, 100.0, 1_000.0)); // 5000
}