// Null safety in Rust // // ggtowell // Oct 31. 2023 use std::cmp; // find the min positive number from an array of 5 integers // because it is an array, there are certainly numbers, but there is no certainty that // there is a positive number. // So the Option "class" is a wrapper around None ie. null ie does not exist, // and an actual value. fn arr_min(v: &[i32; 5]) -> Option { let mut min = None; for e in 0..v.len() { min = match min { None => if v[e]>0 { Some(v[e]) } else { None }, Some(n) => if v[e]>0 {Some(cmp::min(n, v[e])) } else { Some(n) } }; } min } fn main() { let arr = [5,4,3,2,1]; let vmm = arr_min(&arr); // the thing returned is a wrapper than can either have a None or a number println!("{:?}", vmm); // doing it right to handle the possible null value match vmm { None => println!("The array has no positive numbers"), Some(n) => println!("The min positive number is {n}") } // doing it wrong -- or at least the quick and dirty way. println!("The min positive number is {}", vmm.unwrap()); }