wuyangfan 6b7f4955bb docs(exercises): clarify if3 requires uniform branch types
Closes #2211

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 14:08:22 +08:00

59 lines
1.3 KiB
Rust

fn animal_habitat(animal: &str) -> &str {
// TODO: Fix the compiler error in the statement below.
//
// Hint: every `if` / `else if` / `else` branch must produce the same type.
// A floating-point literal, a string, and integers cannot be mixed in one chain.
// For unknown animals, use another integer identifier (for example `4`) instead of
// a string, then keep the habitat checks below unchanged.
let identifier = if animal == "crab" {
1
} else if animal == "gopher" {
2.0
} else if animal == "snake" {
3
} else {
"Unknown"
};
// Don't change the expression below!
if identifier == 1 {
"Beach"
} else if identifier == 2 {
"Burrow"
} else if identifier == 3 {
"Desert"
} else {
"Unknown"
}
}
fn main() {
// You can optionally experiment here.
}
// Don't change the tests!
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gopher_lives_in_burrow() {
assert_eq!(animal_habitat("gopher"), "Burrow")
}
#[test]
fn snake_lives_in_desert() {
assert_eq!(animal_habitat("snake"), "Desert")
}
#[test]
fn crab_lives_on_beach() {
assert_eq!(animal_habitat("crab"), "Beach")
}
#[test]
fn unknown_animal() {
assert_eq!(animal_habitat("dinosaur"), "Unknown")
}
}