0

I would like to pass fn(&str) -> &str (or could be some other types instead of &str, but I am ok with functions returning the same type) as a Hashmap value. My attempt:

fn sum(name: &str) -> &str {
    name
}

fn min(name: &str) -> &str {
    name
}
type A = fn(&str) -> &str;
fn main() {
let a: HashMap<&str, A> = HashMap::from (
        [
        ("sum", sum),
        ("min", min),
        ]
    );
}

Compile time error, in full, I am getting:

error[E0308]: mismatched types
   --> base_engine\src\lib.rs:328:17
    |
328 |         ("min", min),
    |                 ^^^ expected fn item, found a different fn item
    |
    = note: expected fn item `for<'r> fn(&'r str) -> &'r str {sum}`
               found fn item `for<'r> fn(&'r str) -> &'r str {min}`
    = note: different `fn` items always have unique types, even if their signatures are the same
    = help: change the expected type to be function pointer `for<'r> fn(&'r str) -> &'r str`
    = help: if the expected type is due to type inference, cast the expected `fn` to a function pointer: `sum as for<'r> fn(&'r str) -> &'r str`

Any chance to make that work?

Anatoly Bugakov
  • 772
  • 1
  • 7
  • 18

0 Answers0