rust使用函数名作为参数通过match匹配实现计算的代码
Admin | 2023-3-22 15:51:49 | 被阅次数 | 1105
如题所示,直接上代码了。
fn add(a:i32,b:i32) -> i32{
a+b
}
fn mul(a:i32,b:i32) -> i32{
a*b
}
fn less(a:i32,b:i32) -> i32{
a-b
}
fn chu(a:i32,b:i32) -> i32{
a/b
}
type findfunc = fn(a:i32,b:i32) -> i32;
fn matchfunc(s:&str) ->findfunc{
let n = match s{
s if s == "add" => add,
s if s == "mul" => mul,
s if s == "less" => less,
s if s == "chu" => chu,
_ => panic!(),
};
n
}
fn main(){
let result1 = matchfunc("mul")(6,8);
println!("{}",result1);
let result1 = matchfunc("add")(6,8);
println!("{}",result1);
let result1 = matchfunc("less")(6,8);
println!("{}",result1);
let result1 = matchfunc("chu")(6,8);
println!("{}",result1);
let result1 = matchfunc("xyz")(6,8);
println!("{}",result1);
}
/*
输出如下内容
48
14
-2
0
thread 'main' panicked at '异常'
*/