Rust 返回泛型函数指针的函数
假设我有两个功能:Rust 返回泛型函数指针的函数,rust,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", g
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!("!?!?!")
}
}
可以使用枚举表示函数的输出
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!("!?!?!"),
}
}
在使用上述建议之后,这里有一个完整的解决方案
这两个函数甚至没有相同的原型。带有两个参数的函数不是fni64->bool。您到底想在这里实现什么?@E_net4我想更改返回类型get_function_指针,以便为函数返回更通用的签名。我们的目标是动态地将不同形状的函数作为测试属性提供给quickcheck。quickcheck将如何调用它接收的函数?您不能用单个数组或结构替换传入的参数吗?@ChrisEmerson quickcheck接受一个函数是可测试的。消息来源:这看起来很有希望,我会玩一玩!随着函数签名列表的增加,它可能会变得有点麻烦,但是如果没有变量的概念,我们可能会受到限制。
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
}