本文介绍了我怎么可以存储函数指针数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何坚持函数(或函数指针)到一个数组用于测试目的?

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

这code。在<一个href=\"https://play.rust-lang.org/?gist=e89a4cbd1b7f2b73235c624a41167bc8&version=stable&backtrace=0\"相对=nofollow>锈游乐场

这是错误code我得到:

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.

推荐答案

在某些时候日前,各功能被赋予它自己的,独特的类型...这我不记得的原因。结果是,你需要给编译器一个提示(注意函数类型

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];

这篇关于我怎么可以存储函数指针数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 01:14