I'm learning Rust through the official book and rustlings. When reading things seem to make sense but I was kind of lost trying to write code by myself. At the end of chapter 8 there are a couple of exercises and one of them is to write a function that calculates the mean. I'd appreciate any feedback on my code, as there aren't official solutions.
fn median(list: &[i32]) -> Option<f64> {
let mut list = list.to_vec();
if list.is_empty() {
None
} else if list.len() == 1 {
Some(*list.first()? as f64)
} else {
list.sort();
if list.len() % 2 == 1 {
Some(*list.get(list.len() / 2)? as f64)
} else {
Some(
((*list.get(list.len() / 2)? as f64) + (*list.get(list.len() / 2 - 1)? as f64))
/ 2.0,
)
}
}
}
fn main() {
let v = vec![1, 2, 6, 7, 4, 5];
let median = median(&v);
if let Some(num) = median {
println!("The median is {num}")
}
}