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.
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.
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.
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With