如何将函数指针存储在数组中? [英] How can I store function pointers in an array?
本文介绍了如何将函数指针存储在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将函数(或函数指针)粘贴到数组中以进行测试?
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 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 将我的函数(值)视为不同的类型,这让我感到惊讶.
Rust is treating my functions (values) as different types despite having the same signatures, which I find surprising.
推荐答案
在最近的某个时候,每个函数都有自己独特的类型,原因……我不记得了.结果是你需要给编译器一个提示(注意 functions
上的类型):
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]());
}
你也可以这样做:
let functions = vec![foo as fn() -> isize, bar];
这篇关于如何将函数指针存储在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文