added min_and_max function
This commit is contained in:
+42
@@ -41,6 +41,37 @@ fn _get_static_str() -> &'static str {
|
|||||||
"hello"
|
"hello"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
struct EmptyListError;
|
||||||
|
|
||||||
|
// implementing Error for my error to satisfy Box<dyn std::error::Error>
|
||||||
|
// not needed ATM
|
||||||
|
// impl std::error::Error for EmptyListError {}
|
||||||
|
// impl std::fmt::Display for EmptyListError {
|
||||||
|
// fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||||
|
// write!(f, "list must not be empty")
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// Result<...,Box<dyn std::error::Error>> is overkill
|
||||||
|
// this is intuitive enough for caller error detection
|
||||||
|
fn min_and_max(list: &[u32]) -> Result<(u32, u32), EmptyListError> {
|
||||||
|
if list.is_empty() {
|
||||||
|
return Err(EmptyListError);
|
||||||
|
}
|
||||||
|
let mut min:u32 = 100;
|
||||||
|
let mut max:u32 = 0;
|
||||||
|
for i in list {
|
||||||
|
if *i > max {
|
||||||
|
max = *i;
|
||||||
|
}
|
||||||
|
if *i < min {
|
||||||
|
min = *i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((min,max))
|
||||||
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("Hello, world!");
|
println!("Hello, world!");
|
||||||
fmt_debug::test_report();
|
fmt_debug::test_report();
|
||||||
@@ -80,4 +111,15 @@ fn main() {
|
|||||||
let _s6 = String::from(s_lit); //underlying data copied to heap
|
let _s6 = String::from(s_lit); //underlying data copied to heap
|
||||||
|
|
||||||
// todo: Cow
|
// todo: Cow
|
||||||
|
println!("Learning Rust");
|
||||||
|
|
||||||
|
let empty = [];
|
||||||
|
let empty_min_and_max = min_and_max(&empty);
|
||||||
|
assert!(empty_min_and_max.as_ref().is_err());
|
||||||
|
assert!(*(empty_min_and_max.as_ref().err().unwrap()) == EmptyListError);
|
||||||
|
|
||||||
|
let l = [ 1, 2, 10, 100, 50, 75, 36, 21];
|
||||||
|
let l_min_and_max = min_and_max(&l);
|
||||||
|
assert!(l_min_and_max.as_ref().unwrap().0 == 1);
|
||||||
|
assert!(l_min_and_max.as_ref().unwrap().1 == 100);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user