1

Give two functions:

fn foo(x: i32) -> i32 {
    return x + 1;
}

fn bar(x: i32) -> i32 {
    return x + 2;
}

I can create a vector from them and iterate it like so:

let function_vec: Vec<fn(i32) -> i32> = [foo, bar].to_vec();
for function in function_vec {
    let result = function(42);
    println!("{:?}", result);
}

But when putting them as values into a dictionary, I'm doing something wrong:

let function_dict: HashMap<&str, fn(i32) -> i32> = [
        ("A", foo),
        ("B", bar)
    ].iter().cloned().collect();
for (name, function) in function_dict {
    let result = function(42);
    println!("{}: {:?}", name, result);
}

It fails with:

error[E0308]: mismatched types
  --> src/main.rs:14:19
   |
14 |             ("B", bar)
   |                   ^^^ expected fn item, found a different fn item
   |
   = note: expected type `fn(i32) -> i32 {foo}`
              found type `fn(i32) -> i32 {bar}`

error[E0277]: a collection of type `std::collections::HashMap<&str, fn(i32) -> i32>` cannot be built from an iterator over elements of type `(&str, fn(i32) -> i32 {foo})`
  --> src/main.rs:15:27
   |
15 |         ].iter().cloned().collect();
   |                           ^^^^^^^ a collection of type `std::collections::HashMap<&str, fn(i32) -> i32>` cannot be built from `std::iter::Iterator<Item=(&str, fn(i32) -> i32 {foo})>`
   |
   = help: the trait `std::iter::FromIterator<(&str, fn(i32) -> i32 {foo})>` is not implemented for `std::collections::HashMap<&str, fn(i32) -> i32>`

What does the error mean? Why is the type fn(i32) -> i32 {foo} and not just fn(i32) -> i32?

Tobias Hermann
  • 9,936
  • 6
  • 61
  • 134
  • Each named function is still a separate type. In this case, you can explicitly cast them to a function pointer: `("A", foo as fn(i32) -> i32)` and so on. – E_net4 Dec 04 '18 at 09:40
  • @E_net4iskindandwelcoming [Works perfectory](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=6d949dd762b004e0f97f102849230eac), thanks. If you make your comment to an answer, I'll accept it. – Tobias Hermann Dec 04 '18 at 09:50

0 Answers0