this questionに触発されて、Rustの入力データ型エラーを処理する方法について質問したいと思います。たとえば、次の関数では、入力データ型をenum Animal
にする必要があります。ユーザーが実際には定義されていないデータ型や空のデータ型を入力するのはどうでしょうか?入力データの未定義エラー処理
None => None
または_ => None
を試合に追加する必要がありますか?
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,??
}
コンパイラエラー:
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,??
| ^^^^^^^^^^^^^^
コードに入力処理はありません。定義されていない 'enum'バリアントのみです。また、「一致」は網羅的です。 'Animal'のすべてのオプションがカバーされているので、 '_'の必要はありません。あなたの場合のように、他のものは普通の型のエラーになります。 – ljedrz