如何使用函数作为值创建HashMap?

时间:2018-12-04 09:27:43

标签: hashmap rust function-pointers

提供两个功能:

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

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

我可以根据它们创建一个向量,并像so那样对其进行迭代:

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

但是当将它们作为值放入字典时,我做错了:

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);
}

fails带有:

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>`

错误是什么意思?为什么是类型fn(i32) -> i32 {foo}而不仅仅是fn(i32) -> i32

0 个答案:

没有答案