How can I store function pointers in an array? [duplicate]

别来无恙 提交于 2019-11-26 23:20:35

问题


How do you stick functions (or function pointers) into an array for testing purposes?

fn foo() -> isize { 1 }
fn bar() -> isize { 2 }

fn main() {
    let functions = vec![foo, bar];
    println!("foo() = {}, bar() = {}", functions[0](), functions[1]());
}

This code in the Rust playground

This is the error code I get:

error: mismatched types:
 expected `fn() -> isize {foo}`,
    found `fn() -> isize {bar}`
(expected fn item,
    found a different fn item) [E0308]

    let functions = vec![foo, bar];
                              ^~~

Rust is treating my functions (values) as different types despite having the same signatures, which I find surprising.


回答1:


At some point recently, each function was given its own, distinct type for... reasons that I don't recall. Upshot is that you need to give the compiler a hint (note the type on functions):

fn foo() -> isize {
    1
}
fn bar() -> isize {
    2
}
fn main() {
    let functions: Vec<fn() -> isize> = vec![foo, bar];
    println!("foo() = {}, bar() = {}", functions[0](), functions[1]());
}

You can also do this like so:

let functions = vec![foo as fn() -> isize, bar];


来源:https://stackoverflow.com/questions/28151073/how-can-i-store-function-pointers-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!