Trying to build a HashMap
of Command
and Function
where the command is a RegEx
and once the user post a phrase matching this a given Regex (hashmap key) the programe will execute the function associated with this command (hashmap value).
I drafted the below, but has 2 issues with it:
- Can not add RegEx to the HashMap
error[E0599]: no method named `insert` found for struct `std::collections::HashMap<regex::re_unicode::Regex, fn(i32, i32) -> i32>` in the current scope
--> src\main.rs:124:14
|
124 | commands.insert(
| ^^^^^^ method not found in `std::collections::HashMap<regex::re_unicode::Regex, fn(i32, i32) -> i32>`
|
::: C:\Users\Yara Yousef\.cargo\registry\src\github.com-1ecc6299db9ec823\regex-1.3.7\src\re_unicode.rs:136:1
|
136 | pub struct Regex(Exec);
| -----------------------
| |
| doesn't satisfy `regex::re_unicode::Regex: std::cmp::Eq`
| doesn't satisfy `regex::re_unicode::Regex: std::hash::Hash`
|
= note: the method `insert` exists but the following trait bounds were not satisfied:
`regex::re_unicode::Regex: std::cmp::Eq`
`regex::re_unicode::Regex: std::hash::Hash`
- Casting the RegEx capture as number:
error[E0605]: non-primitive cast: `regex::re_unicode::Match<'_>` as `i32`
--> src\main.rs:140:44
|
140 | let sum_num = function(caps.get(2).unwrap() as i32, caps.get(4).unwrap() as i32);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
My code is:
use regex::Regex;
use std::collections::HashMap;
fn sum(x: i32, y: i32) -> i32 {
x + y
}
fn main() {
let mut commands: HashMap<Regex, fn(x: i32, y: i32) -> i32> = HashMap::new();
commands.insert(
Regex::new(r#"(?xi)
(What\sis|What's|Calculate|How much is)
\s(\d)
\s(\+|and|plus|)
\s(\d)
"#).unwrap(),
sum
);
let phrase = "what is 1 + 2";
for (command, function) in &commands {
match command.is_match(phrase) {
true => {
for caps in command.captures(phrase) {
let sum_num = function(caps.get(2).unwrap() as i32, caps.get(4).unwrap() as i32);
println!("Sum of {} and {} is {}",
caps.get(2).unwrap(), caps.get(4).unwrap(), sum_num);
}
},
false => {},
}
}