Inspired by this question, I want to ask about how to handle input data type error in Rust. For example, the following function require input data type to be enum Animal
. How about the user actually give an input with not-defined data type or even a empty one.
Should I add a None => None
or _ => None
in the match?
use std::fmt;
use std::io::prelude::*;
pub enum Animal {
Cat(String),
Dog,
}
impl fmt::Display for Animal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Animal::Cat(ref c) => f.write_str("c"),
Animal::Dog => f.write_str("d"),
}
}
}
fn main() {
let p: Animal = Animal::Cat("whiskers".to_owned()); // yes, work!
let p: Animal = Animal::BadCat("whiskers".to_owned()); // Badcat not defined,??
}
Compiler error:
error: no associated item named `BadCat` found for type `Animal` in the current scope
--> <anon>:20:25
|
20 | let p: Animal = Animal::BadCat("whiskers".to_owned()); // Badcat not defined,??
| ^^^^^^^^^^^^^^