返回泛型函数指针的函数

时间:2017-03-02 16:32:38

标签: rust

说我有两个功能:

fn function_with_one_argument(one: i64) -> bool{
    one==one // irrelevant
}

fn function_with_two_arguments(one: i64, two: i64) -> bool {
    one==two // irrelevant
}

给定不同的输入值,我想返回一个不同的函数指针:

fn main() {
    println!("\n\n{:?}\n\n", get_function_pointer(1)(321));
    println!("{:?}", get_function_pointer(2)(321/*, 321*/));
}

如何表示返回值以返回指向不同形状函数的指针?

fn get_function_pointer(id: i64) -> /***/(fn(i64) -> bool)/***/ {
    match id {
        1 => function_with_one_argument,
        // 2 => function_with_two_arguments, /*How do we make this work?*?
        _ => panic!("!?!?!")
    }
}

2 个答案:

答案 0 :(得分:5)

您可以使用枚举来表示函数的输出

enum Either<T, U> {
    Left(T),
    Right(U),
}

fn function_with_one_argument(one: i64) -> bool {
    one == one // irrelevant
}

fn function_with_two_arguments(one: i64, two: i64) -> bool {
    one == two // irrelevant
}

fn get_function_pointer(id: i64) -> Either<fn(i64) -> bool, fn(i64, i64) -> bool> {
    match id {
        1 => Either::Left(function_with_one_argument),
        2 => Either::Right(function_with_two_arguments),
        _ => panic!("!?!?!"),
    }
}

答案 1 :(得分:2)

使用上面enum的建议后,这是一个完整的解决方案。

extern crate quickcheck;
use quickcheck::{QuickCheck, Testable};
use std::collections::HashMap;

fn main() {
    let mut property_map = HashMap::new();
    property_map.insert("one", Property::One { func: one_argument });
    property_map.insert("two", Property::Two { func: two_arguments });

    test_property("one", &property_map);
    test_property("two", &property_map);
}

enum Property {
    One { func: fn(i64) -> bool },
    Two { func: fn(i64, i64) -> bool },
}

fn test_property(property: &str, property_map: &HashMap<&str, Property>) {
    match property_map.get(property) {
        Some(p) => fetch_property_and_run_quickcheck(p),
        None => println!("No matching property in property_map"),
    };
}

fn fetch_property_and_run_quickcheck(property: &Property) {
    match *property {
        Property::One { func: prop_to_test } => run_quickcheck(prop_to_test),
        Property::Two { func: prop_to_test } => run_quickcheck(prop_to_test),
    };
}

fn run_quickcheck<A>(property: A)
    where A: Testable
{
    QuickCheck::new().quickcheck(property);
}

fn one_argument(one: i64) -> bool {
    println!("testing one_argument() with {}", one);
    one == one // irrelevant
}

fn two_arguments(one: i64, two: i64) -> bool {
    println!("testing two_arguments() with {} and {}", one, two);
    one == one && two == two // irrelevant
}