2

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,??
   |                         ^^^^^^^^^^^^^^
Community
  • 1
  • 1
enaJ
  • 1,565
  • 5
  • 16
  • 29
  • 1
    There is no input handling in your code - only an undefined `enum` variant. Also, the `match` is exhaustive; no need for `_`, since all options for `Animal` are covered - anything else would be a plain type error, like in your case. – ljedrz Oct 21 '16 at 06:03

1 Answers1

4

Rust is a strongly1, statically typed, compile-time type checked language.

This means that unlike, say, Python, it is impossible for a user to pass an invalid type to your function (unless they're passing data that has been invalidly coerced via unsafe, but you can't reasonably detect this. See my post about incorrect transmutations to bool). You do not need to worry about this.

In the more general case, the only time you need to worry about type variant checking in Rust is when receiving data from outside Rust, e.g. through a configuration or data file, or else an FFI function. In these cases, it's customary to return a Result<Animal,ErrorMessage> of some sort to indicate bad data. However, in some cases, especially in FFI, if you receive data that's particularly malformed it may be acceptable to panic!.

This type of checking usually does not involve match statements on an enum, but rather more fundamental checks such as assertions about string or integer comparisons being one of a set of known values that you're trying to reinterpret to a higher level enum type.


1 There's some inconsistency and disagreement on what "strongly typed" actually means, in this case I'm using it to mean "few if any implicit type coercions".

Community
  • 1
  • 1
Linear
  • 21,074
  • 4
  • 59
  • 70