I'm writing a simple program to parse lines read from a file. As I'm new to Rust, I wonder if I'm creating too much boilerplate.

A sample line in the file looks like this: pqrXYZ12a9. Char at position 8 (starting from 0) can be a, b, or c and let's say it represents some sort of "category".

I think of modelling that specific field with an enum. Then I realised I need a function to parse the actual value to the specific variant.

Here's my code - questions afterwards:

enum Category {    

fn parse_category(line: String) -> Category {    
    let category = &line[8 .. 9];                 
    match category {    
        "a" => Category::A,    
        "b" => Category::B,    
        "c" => Category::C,    
        _ => panic!(),    

fn main() {    
    let test_string = String::from("pqrXYZ12a9");    

    match parse_category(test_string) {      
        Category::A => println!("Cat A"),   
        Category::B => println!("Cat B"),    
        Category::C => println!("Cat C"),    

Things I'm not sure about, specifically are:

  • Can I avoid creating a parse_category function, and assign the specific letter to the Category variants? In fact, should I or should I not? Something like:

    // does not compile enum Category { A = 'a', ... }

  • Is there a way to "name the slice" in parse_category? I'd like to avoid putting magical numbers here and there and have all fields defined somewhere together. In Python I'd create a slice object such as category_field = slice(8, 9) and then pass it as line[category_field].

  • Any other feedback is welcome.
  • \$\begingroup\$ &line[8 .. 9] can make your code panic, I think you should use line.chars().position(8);. Also, I don't think make a function to only parse one char is good. You case is too minimal to give any precise advice. \$\endgroup\$ – Stargateur Apr 14 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.