0

I want to parse some text that I want to do logic on (count, sort, filter, and such). Should I parse the text input to a "dynamic struct"? From what I've gathered when searching the web this is not entirely straightforward to solve in Rust.

I have this input from a file:

#1:PERSON["#2", 180, 85, 28]
#2:EYES["green", false]
#3 ...

I want to instantiate Person structs, preferably without having to match on every possible struct:

struct ParseResult {
    class: String,
    params: String,
}

struct Person {
    eyes: Eyes,
    age: i32,
    weight: i32,
    height: i32,
}

struct Eyes {
    color: String,
    glasses: bool,
}

fn parse(input: String) -> Result<Person, &'static str> {
    // ...parsing magic
    let x = ParseResult {
        class: "PERSON".to_string(),
        params: "\"#2\", 180, 85, 28, \"#3\"".to_string(),
    };

    // I don't want to do this if I can avoid it:
    let new_struct = match x.class {
        "PERSON" => { /* instantiate new person */ }
        "EYES" => { /* instantiate new eyes */ }
        // ...
    };

    // ...

    Ok(new_struct)
}

#[test]
fn parse_input() {
    let p = parse("#1:PERSON[\"#2\", 180, 85, 28]\n#2:EYES[\"green\", false]".to_string()).unwrap();
    assert_eq!(p.age, 28);
}

Is this the correct way to think about this problem? Should I think about this issue in some other way?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
mottosson
  • 3,283
  • 4
  • 35
  • 73
  • What do you expect the type of `new_struct` to be? Either `Person` and `Eyes` need to have a common trait and `new_struct` will be a boxed trait object, or (more recommended) you should make an enum type of which `Person` and `Eyes` are possibilities. Either way, that case statement is the right way to approach this problem. – Silvio Mayolo Jul 05 '19 at 21:29
  • How can you avoid that `match`? I mean, even in Python (my go-to "dynamic" language), you're still going to have to write code that parses the tag and dispatches to either the `Person` or `Eyes` constructor. – trent Jul 06 '19 at 11:10
  • I've implemented this in Typescript where I could create a factory function where I basically took all classes and put them into a hash map and from the class name dynamically created a class: See #2 here https://stackoverflow.com/a/34656123/1644471 – mottosson Jul 06 '19 at 15:10

0 Answers0