Coding within Rust is definitely slightly different than coding with JavaScript or Typescript. With JS, one can get away with a lot of stuff. With TS, one can get away with less than JS. But Rust, seems to be very less. I don’t think I’ve encountered so many Result, match statements or Options equivalents in JS or TS.

I also don’t think I’ve encountered any reason to use enums in Rust. I am just starting to use them more with TypeScript. But could I possibly use them more in Rust?

Long story short, I discovered that enums could be used to handle errors. I originally discovered this when I was searching for a way to to safe union types in Rust. It turns out there wasn’t any, but someone pointed to use enums for union types. So I could possibly have an enum that has a valid value and a handled error value. Then I would run a match on those enums for the valid value.

So, I started to explore using enums in my media organizer project to handle errors better.

I discovered that the amount of panic!s that I have wasn’t a good amount, and the panic!s weren’t helpful for the runtime of the program. The program should still be able to run if the media organizer couldn’t sort a file. So I changed out the panic!s with enums that have valid values and error values. The following code bit is and example showing how I handled things.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
enum ExampleEnum {
  ValidData(String),
  Error(String)
}

fn example_handle_enum(ex_param: ExampleEnum) {
  match ex_param {
    ExampleEnum::ValidData(data) => {...}
    ExampleEnum::Error(Error) => {...}
  }
}

Now, my media organizer program can run without errors! I like that a lot.