gpt4 book ai didi

rust - 返回通用函数指针的函数

转载 作者:行者123 更新时间:2023-11-29 08:22:08 25 4
gpt4 key购买 nike

假设我有两个函数:

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!("!?!?!"),
}
}

关于rust - 返回通用函数指针的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42560865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com