In the last post we created a simple program that would accept an input like 5+5
and calculates the result.
In this post we will improve this program.
To prepare for adding more operators we need to improve the input-parsing.
Currently, we just split the input-string at the plus-sign.
If we want to know the operator, we have to choose another approach.
In this case I chose regex:
#[derive(Debug)]
struct Operation {
left: i32,
operator: char,
right: i32,
}
impl Operation {
fn from_string(input: &String) -> Option<Operation> {
let regex = Regex::new(r"^\s*(\d+)\s*([+])\s*(\d+)\s*$").unwrap();
regex.captures(&input).map(|capture| Operation {
left: (&capture[1]).parse().unwrap(),
operator: (&capture[2]).parse().unwrap(),
right: (&capture[3]).parse().unwrap(),
})
}
}
As you can see we have a new thing called struct
in the code.
If you are coming from a language like Java or Typescript, a struct can be seen as a class without any methods.
This struct is called Operation
and as the name suggests it holds an operation.
The fields left
and right
are both typed as an i32
or in other words a “signed 32-bit integer”.
The field operator
is a char
since we only use one character for an operator.
In rust strings
and chars
are utf-8, therefore a char
can contain one unicode codepoint, not just a byte.
Continue reading