RUST 学习日记 第19课 ——函数(二)
RUST 学习日记 第19课 ——函数(二)
0x00 回顾与开篇
上节初步了解了Rust的函数,这节课继续介绍Rust的高阶函数——函数作为参数和函数作为返回值的两种形式。
0x01 type定义别名
在Rust中,我们可以使用type关键字来为Rust的原始类型或者自定义类型定义别名。
示例代码如下:
type Int = i32;
type Float = f32;
type Double = f64;
type Char = char;
let a: Int = 3;
let b: Float = 4.5;
let c: Double = 134.6753453424234231;
let d: Char = '我';
dbg!(a);
dbg!(b);
dbg!(c);
dbg!(d);
代码运行结果:
a = 3
b = 4.5
c = 134.6753453424234
d = '我'
上面的代码可以看到,咱们把i32类型定义别名为Int类型,f32类型定义别名为Float类型,f64类型定义别名为Double类型,char类型定义别名为Char类型。
0x02 函数作为参数
当Rust的函数作为参数时,建议使用type关键字为函数指针类型定义别名。其目的是为了提升代码的可读性。下面我通过一个例子讲解将函数作为参数的例子。
/// 函数声明别名
type Calc = fn(i32, i32) -> i32;
/// 操作运算(别名)
fn operation_alias(calc: Calc, a: i32, b: i32) -> i32 {
return calc(a, b);
}
/// 操作运算
fn operation(calc: fn(i32, i32) -> i32, a: i32, b: i32) -> i32 {
return calc(a, b);
}
/// 加法
fn add(a: i32, b: i32) -> i32 {
return a + b;
}
/// 乘法
fn mul(a: i32, b: i32) -> i32 {
return a * b;
}
fn main() {
let a = 5;
let b = 3;
let add_result = operation_alias(add, a, b);
let mul_result = operation(mul, a, b);
dbg!(add_result);
dbg!(mul_result);
}
代码运行结果:
add_result = 8
mul_result = 15
代码解释:
首先,使用type关键字为函数指针类型fn(i32,i32)->i32起一个别名为Calc。然后又定义了一个函数operation_alias,它有三个参数,其中第一个参数为Calc类型,第二个和第三个参数是i32类型。紧接着又定义了一个函数operation,它也有三个参数,与operation_alias一样。不同的是,operation的第一个参数没有使用别名,而是使用了原始的函数指针类型,在可读性上可能比较差。最后按照fn(i32,i32)->i32形式,分别定义了add和mul函数来计算加法和乘法。
main函数中,分别调用operation_alias和operation方法,计算a和b的值。
0x03 函数作为返回值
当Rust的函数作为返回值时,建议使用type关键字为函数指针类型定义别名。其目的是为了提升代码的可读性。下面我通过一个例子讲解将函数作为返回值的例子。
/// 函数声明别名
type Calc = fn(i32, i32) -> i32;
/// 根据字符串获取函数(别名)
fn get_operation_alias(s: &str) -> Calc {
if s == "add" {
add
} else {
mul
}
}
/// 根据字符串获取函数
fn get_operation(s: &str) -> fn(i32, i32) -> i32 {
if s == "add" {
add
} else {
mul
}
}
/// 加法
fn add(a: i32, b: i32) -> i32 {
return a + b;
}
/// 乘法
fn mul(a: i32, b: i32) -> i32 {
return a * b;
}
fn main() {
let a = 4;
let b = 6;
let add_result = get_operation_alias("add")(a, b);
let mul_result = get_operation("mul")(a, b);
dbg!(add_result);
dbg!(mul_result);
}
代码运行结果:
add_result = 10
mul_result = 24
代码解释:
首先,使用type关键字为函数指针类型fn(i32,i32)->i32起一个别名为Calc。然后又定义了一个函数get_operation_alias,它只有一个参数,根据参数返回指定的函数。紧接着又定义了一个函数get_operation,它也只有一个参数,与get_operation_alias一样。不同的是,get_operation的返回值使用了原始的函数指针类型,在可读性上可能比较差。最后按照fn(i32,i32)->i32形式,分别定义了add和mul函数来计算加法和乘法。
main函数中,分别调用get_operation_alias和get_operation方法,计算a和b的值。
0x04 小结
本节介绍了Rust高阶函数的两种形式——函数作为参数和函数作为返回值。当函数作为参数或者作为返回值时,建议使用type类型定义别名。
0x04 本节源码
019 · StudyRust - 码云 - 开源中国 (gitee.com)
下节预告—— 闭包。