Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 751
Andrew Wagner Avatar asked Jan 26 '15 13:01

Andrew Wagner


People also ask

Can we store pointers in an array?

An array of pointers is an array that consists of variables of pointer type, which means that the variable is a pointer addressing to some other element. Suppose we create an array of pointer holding 5 integer pointers; then its declaration would look like: int *ptr[5]; // array of 5 integer pointer.

How do you pass an array of pointers to a function in C++?

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.

What is the use of pointer to an array in C?

Master C and Embedded C Programming- Learn as you go Unary operator ( * ) is used to declare a variable and it returns the address of the allocated memory. Pointers to an array points the address of memory block of an array variable. The following is the syntax of array pointers.


1 Answers

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];
like image 129
DK. Avatar answered Sep 18 '22 11:09

DK.