We have already seen in this chapter how enums can be somewhat tricky to handle. Thankfully, we can use match on an enum:
enum MyFirstEnum { TupleType(f32, i8, String), StructType {varone: i32, vartwo: f64}, NewTypeTuple(i32), SomeVarName } fn tuple_type(v: f32, c: i8, st: String) {//code} fn struct_type(v1: i32, v2: f64) {//code} fn new_type_tuple(n: i32) {//code} fn process_varname() {//code} fn match_enum_code(e: MyFirstEnum) { match e { MyFirstEnum::SomeVarName => process_varname(), MyFirstEnum::TupleType(f,i,s) => tuple_type(f,i,s), MyFirstEnum::StructType(v1,v2) => struct_type(v1,v2), MyFirstEnum::NewTypeTuple(i) => new_type_tuple(i) }; }
You will notice that in this example, _ is not included. That's because we explicitly match against all the possible choices of the enum, so we don't need a catch-all case. If, for instance, we missed NewTypeTuple, the code would need to include a catch-all:
fn match_enum_code(e:MyFirstEnum) { match e { MyFirstEnum::SomeVarName => process_varname(), MyFirstEnum::TupleType(f,i,s) => tuple_type(f,i,s), MyFirstEnum::StructType(v1,v2) => struct_type(v1,v2), _ => return // breaks out of the match }; }