Dzwebs.Net

撰写电脑技术杂文十余年

rust使用函数名作为参数通过match匹配实现计算的代码

Admin | 2023-3-22 15:51:49 | 被阅次数 | 913

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

  如题所示,直接上代码了。

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 '异常'
*/

该杂文来自: 最新技术

上一篇:rust泛型T构造枚举enum的通用字段及impl构造自定

下一篇:rust控制台读取键盘输入并判断输入字符

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计