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?