Module lessons (2/2)
Scalar, Tuple, Array and String Slice types
The map of basic types on the Stack
Understand size, overflow safety, and fixed layout before introducing the Heap.
All Rust primitive types live entirely on the Stack of known compile size. No implicit numeric conversion happens behind your back: if you add i32 and u64, you must make the intention explicit with as or TryFrom.
1. Integers (i32, u8, usize) and explicit overflow
Rust offers signed (i8..i128, isize) and unsigned (u8..u128, usize) integers. The default type for an integer literal is i32, while usize represents collection sizes and indices based on architecture (32 or 64 bits):
fn main() {
let temperature: i32 = -12;
let byte_mask: u8 = 0xff;
let index: usize = 3;
let big_number = 1_000_000_i64; // suffisso di tipo + separatori leggibili
println!("{} {} {} {}", temperature, byte_mask, index, big_number);
}2. Floating Point (f64), Booleans and char Unicode
Unlike C where char is worth 1 ASCII byte, a Rust char always takes up 4 bytes and represents a single Unicode Scalar Value (including accented letters and emoji):
fn main() {
let ratio: f64 = 0.618;
let active: bool = true;
let initial: char = 'È';
let crab: char = '🦀';
println!("ratio={} active={} {} {}", ratio, active, initial, crab);
}3. Tuple: heterogeneity on the Stack
A tuple groups values of different types into a fixed length. You can extract them by position (pair.0) or by destructuring with let (a, b) = ...:
fn min_max(a: i32, b: i32) -> (i32, i32) {
if a <= b { (a, b) } else { (b, a) }
}
fn main() {
let coords: (f64, f64, &str) = (45.46, 9.19, "Milano");
let (lat, lon, city) = coords;
let bounds = min_max(42, 7);
println!("{}: {}, {} | bounds={:?}", city, lat, lon, bounds);
}4. Array [T; N] and Slice &[T] / &str
An array [i32; 4] has fixed length part of the type; a slice &[i32] or &str is instead a view (pointer + length) on contiguous data without possessing it:
fn main() {
let ports: [u16; 3] = [80, 443, 8080];
let secure_slice: &[u16] = &ports[1..];
let greeting: &str = "Ciao Rust";
println!("Prima porta: {}, slice {:?}, msg={}", ports[0], secure_slice, greeting);
}Practical exercises
Write a function clamp_percent(value: u8) -> u8 that returns 100 if value > 100, otherwise value. Also declare in main a variable grade: u8 = 120 and print clamp_percent(grade).
Show hint
Remember that if ... else ... in Rust is an expression that directly returns the chosen branch.
Solution available after 3 attempts
Write swap_pair(pair: (i32, &str)) -> (&str, i32) which receives a tuple (numero, testo) and returns a new inverted tuple (testo, numero) by destructuring let (num, text) = pair;.
Show hint
You can write let (num, text) = pair; and then (text, num) as the return expression.
Solution available after 3 attempts
Create an array scores: [i32; 4] = [10, 20, 30, 40] in main, extract the middle sub-slice mid: &[i32] = &scores[1..3] and print its length with mid.len().
Show hint
The array annotation is [i32; 4] while the partial view is &scores[1..3].
Solution available after 3 attempts
Check for understanding
How much memory does the char type take up in Rust and what exactly does it represent?
let symbol: char = '🦀';What value does slice take on in the following extraction?
let nums = [5, 10, 15, 20, 25];
let slice = &nums[1..4];