Language basics
Basic types
Rust is statically typed, but the compiler infers most types. Integers have an explicit size: i32 (signed, 32 bits, the default), u64 (unsigned), usize (pointer-sized, used for indexes). Floats are f64 (default) and f32.
rust
fn main() { let count: u32 = 42; let price: f64 = 101.25; let is_call = true; let currency = '€'; // char : un caractère Unicode, entre apostrophes // Aucune conversion implicite : on convertit avec `as`. let total = price * count as f64; println!("{count} x {price} {currency} = {total} (call: {is_call})");}Two native compound types. A tuple groups values of different types, accessed by position. An array holds a fixed number of elements of the same type, known at compile time.
rust
fn main() { let quote: (&str, f64) = ("EURUSD", 1.0842); let (pair, rate) = quote; // déstructuration println!("{pair} = {rate} (ou {})", quote.1); let tenors: [u32; 4] = [1, 2, 5, 10]; println!("{} tenors, le plus long : {} ans", tenors.len(), tenors[3]);}[u32; 4] reads "array of 4 u32". An out-of-bounds access triggers a panic, never a random memory read.Your turn
Compute the average of the 5 prices in the array and print it. Mind the types.
src/main.rs
fn main() { let prices: [f64; 5] = [100.0, 102.5, 99.0, 101.0, 97.5]; let sum = prices[0] + prices[1] + prices[2] + prices[3] + prices[4]; // divise par le nombre d'éléments}prices.len() returns a usize, which cannot be divided with an f64 directly.
solution
fn main() { let prices: [f64; 5] = [100.0, 102.5, 99.0, 101.0, 97.5]; let sum = prices[0] + prices[1] + prices[2] + prices[3] + prices[4]; let average = sum / prices.len() as f64; println!("average = {average}");}We convert the length explicitly with as f64. We will soon see a for loop and then iterators (prices.iter().sum()) to avoid writing every index.