if3.rs (1060B)
1 fn animal_habitat(animal: &str) -> &str { 2 let identifier = if animal == "crab" { 3 1 4 } else if animal == "gopher" { 5 2 6 } else if animal == "snake" { 7 3 8 } else { 9 // Any unused identifier. 10 4 11 }; 12 13 // Instead of such an identifier, you would use an enum in Rust. 14 // But we didn't get into enums yet. 15 if identifier == 1 { 16 "Beach" 17 } else if identifier == 2 { 18 "Burrow" 19 } else if identifier == 3 { 20 "Desert" 21 } else { 22 "Unknown" 23 } 24 } 25 26 fn main() { 27 // You can optionally experiment here. 28 } 29 30 #[cfg(test)] 31 mod tests { 32 use super::*; 33 34 #[test] 35 fn gopher_lives_in_burrow() { 36 assert_eq!(animal_habitat("gopher"), "Burrow") 37 } 38 39 #[test] 40 fn snake_lives_in_desert() { 41 assert_eq!(animal_habitat("snake"), "Desert") 42 } 43 44 #[test] 45 fn crab_lives_on_beach() { 46 assert_eq!(animal_habitat("crab"), "Beach") 47 } 48 49 #[test] 50 fn unknown_animal() { 51 assert_eq!(animal_habitat("dinosaur"), "Unknown") 52 } 53 }