Rust 函数

释放双眼,带上耳机,听听看~!

Rust 是一门多范式的编程语言,但 Rust 的编程风格是更偏向于函数式的,函数在 Rust 中是“一等公民”。这意味着,函数是可以作为数据在程序中进行传递。

跟 C/C++/Go 一样,Rust 程序也有一个唯一的程序入口 main 函数,之前在 hello world 例子中已经见到过了:


1
2
3
4
1fn main() {
2
3}
4

Rust 使用 fn 关键字来声明和定义函数,后面跟着函数名,一对括号是因为这函数没有参数,然后是一对大括号代表函数体。下面是一个叫做 foo 的函数:


1
2
3
4
1fn foo() {
2
3}
4

如果函数有返回值,在括号后面加上箭头 -> ,接着是返回类型:


1
2
3
4
5
6
7
8
1fn main() {
2    println!("{:?}", add(1, 2));
3}
4
5fn add(x: i32, y: i32) -> i32 {
6    x + y
7}
8

add 函数可以将两个数值加起来并将结果返回。

语句和表达式

Rust 主要是一个基于表达式的语言。只有两种语句,其他的一切都是表达式。

这又有什么区别的?表达是返回一个值,而语句不是。这就是为甚恶魔这里我们以“不是所有控制路劲都返回一个值”结束:x + 1; 语句不返回一个值。Rust 中有两种类型的语句:“声明语句”和“表达式语句”。其余一切都是表达式。

声明语句

在一些语言中,变量绑定可以被写成一个表达式,不仅仅是语句。例如 Ruby:


1
2
1x = y = 5
2

然而,在 Rust 中,使用 let 引入一个绑定并不是一个表达式。下面的代码会产生一个编译时错误:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1let x = (let y = 5);
2    Blocking waiting for file lock on build directory
3   Compiling hello_world v0.1.0 (yourpath/hello_world)
4error: expected expression, found statement (`let`)
5 --> main.rs:2:14
6  |
72 |     let x = (let y = 5);
8  |              ^^^
9  |
10  = note: variable declaration using `let` is a statement
11
12error: aborting due to previous error
13
14error: Could not compile `hello_world`.
15

编译器告诉我们这里它期望看到表达式的开头,而 let 只能开始一个语句,不是一个表达式。

注意赋值一个已经绑定过的变量(例如 y = 5)仍然时一个表达式,即使它的(返回)值并不是特别有用。不像其他语言中赋值语句返回它赋的值(例如,前面例子中的 5 ),在 Rust 中赋值的值是一个空元组 ():


1
2
3
4
1let mut y = 5;
2
3let x = (y = 6); // x has the value `()`, not `6`
4

表达式语句

表达式语句的目的是把任何表达式变为语句。在实践中,Rust 语法期望语句后面跟其他语句。这意味着用分号来分隔各个表达式。着意味着 Rust 看起来很像大部分其他使用分号作为语句结尾的语言,并且你会看到分号出现在几乎每一行 Rust 代码。

那么我们说“几乎”的例外是什么呢?比如:


1
2
3
4
1fn add_one(x: i32) -> i32 {
2    x + 1;
3}
4

我们的函数声称它返回一个 i32,不过带有一个分号的话,它将返回一个 ()。Rust 意识到这可能不是我们想要的,并在我们看到的错误中建议我们去掉分号:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1   Compiling hello_world v0.1.0 (yourpath/hello_world)
2error[E0269]: not all control paths return a value
3 --> main.rs:1:1
4  |
51 | fn add_one(x: i32) -> i32 {
6  | ^
7  |
8help: consider removing this semicolon:
9 --> main.rs:2:10
10  |
112 |     x + 1;
12  |          ^
13
14error: aborting due to previous error
15
16error: Could not compile `hello_world`.
17fn add_one(x: i32) -> i32 {
18    x + 1
19}
20

函数参数

参数声明

Rust 的函数参数声明和一般的变量声明非常相似:参数名加上冒号再加上参数类型,不过不需要 let 关键字。例如这个程序将两个数相加并打印结果:


1
2
3
4
5
6
7
8
1fn main() {
2    print_sum(5, 6);
3}
4
5fn print_sum(x: i32, y: i32) {
6    println!("sum is: {}", x + y);
7}
8

在调用函数和声明函数时,多个参数需要用逗号 , 分隔。与 let 不同的是,普通变量声明可以省略变量类型,而函数参数声明则不能省略参数类型。下面的代码不能够工作:


1
2
3
4
5
6
7
8
1fn main() {
2    print_sum(5, 6);
3}
4
5fn print_sum(x, y) {
6    println!("sum is: {}", x + y);
7}
8

编译器将会给出以下错误:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
1   Compiling hello_world v0.1.0 (yourpath/hello_world)
2error: expected one of `:` or `@`, found `,`
3 --> main.rs:5:15
4  |
55 | fn print_sum(x, y) {
6  |               ^
7
8error: expected one of `:` or `@`, found `)`
9 --> main.rs:5:18
10  |
115 | fn print_sum(x, y) {
12  |                  ^
13
14error[E0425]: unresolved name `x`
15 --> main.rs:6:28
16  |
176 |     println!("sum is: {}", x + y);
18  |                            ^
19<std macros>:2:27: 2:58 note: in this expansion of format_args!
20<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
21main.rs:6:5: 6:35 note: in this expansion of println! (defined in <std macros>)
22
23error[E0425]: unresolved name `y`
24 --> main.rs:6:32
25  |
266 |     println!("sum is: {}", x + y);
27  |                                ^
28<std macros>:2:27: 2:58 note: in this expansion of format_args!
29<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
30main.rs:6:5: 6:35 note: in this expansion of println! (defined in <std macros>)
31
32error[E0061]: this function takes 0 parameters but 2 parameters were supplied
33 --> main.rs:2:5
34  |
352 |     print_sum(5, 6);
36  |     ^^^^^^^^^^^^^^^ expected 0 parameters
37
38error: aborting due to previous error
39
40error: Could not compile `hello_world`.
41

这是一个有意而为之的设计决定。即使像 Haskkell 这样的能够全程序推断的语言,注明类型也经常作为一个最佳实践被建议。不过,还有一种特殊的函数,闭包(closure, lambda),类型标注是可选的。将在后续章节中介绍闭包。

函数作为参数

在 Rust 中,函数是一等公民(可以存储在变量/数据结构、可以作为参数传入函数、可以作为返回值),所以函数参数不仅可以是一般类型,也可以是函数。如:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1fn main() {
2    let xm = "xiaoming";
3    let xh = "xiaohong";
4    say_what(xm, hi);
5    say_what(xh, hello);
6}
7
8fn hi(name: &str) {
9    println!("Hi, {}.", name);
10}
11
12fn hello(name: &str) {
13    println!("Hello, {}.", name);
14}
15
16fn say_what(name: &str, func: fn(&str)) {
17    func(name)
18}
19

这个例子中,hi 函数和 hello 函数都只有一个 &str 类型的参数而且没有返回值。say_what 函数有两个参数,一个是 &str 类型,另一个是函数类型(function type),它只有一个 &str 类型的参数且没有返回值的行数类型。

模式匹配

又一次提到了模式,模式匹配给 Rust 增添了许多灵活性。模式匹配不仅可以用在变量申明中,也可以用在函数参数申明中,如:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1fn main() {
2    let xm = ("xiaoming", 54);
3    let xh = ("xiaohong", 66);
4    print_id(xm);
5    print_id(xh);
6    print_name(xm);
7    print_age(xh);
8    print_name(xm);
9    print_age(xh);
10}
11
12fn print_id((name, age): (&str, i32)) {
13    println!("I'm {},age {}.", name, age);
14}
15
16fn print_age((_, age): (&str, i32)) {
17    println!("My age is  {}", age);
18}
19
20fn print_name((name,_): (&str, i32)) {
21    println!("I am  {}", name);
22}
23

这是一个元组(Tuple)匹配的例子,当然也可以是其他可以在 let 语句中使用的类型。参数的匹配跟 let 语句的匹配一样,也可以使用下划线表示丢弃一个值。

返回值

在 Rust 中,任何函数都有放回类型,当函数返回时,会返回一个该类型的值。再来看看 main 函数:


1
2
3
4
1fn main() {
2
3}
4

函数的返回值类型是在参数列表后,加上箭头 -> 和类型来指定的。不过,一般我们看到的 main 函数的定义并没有这么做。这是因为 ‘main’ 函数的返回值是 (), 在 Rust 中,当一个函数返回 () 时,可以省略。main 函数的完整形式如下:


1
2
3
4
1fn main() -> () {
2
3}
4

main 函数的返回值类型是 (), 它是一个特殊的元组——一个没有元素的元组,称之为 unit,它表示一个函数没有任何信息需要返回。() 类型,类似于 C/C++、Java、C# 中的 void 类型。

下面看一个有返回值的例子:


1
2
3
4
5
6
7
8
9
1fn main() {
2    let a = 123;
3    println!("{}", inc(a));
4}
5
6fn inc(n: i32) -> i32 {
7    n + 1
8}
9

这个例子中,inc 函数有一个 i32 类型的参数和返回值,作用是将参数加 1 返回。需要注意的是 inc 函数中只有一个 n + 1 一个表达式,并没有像 C/C++ 等语言有显示的 return 语句返回一个值。这是因为,与其他语言不同,Rust 是基于表达式的语言,函数中最后一个表达式的值,默认作为返回值(注意:没有分号 :)。稍后会介绍语句和表达式。

return 关键字

Rust 也有 return 关键字,不过一般用于提早返回。看这个例子:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1fn main() {
2    let a = [1, 2, 3, 4, 8, 9];
3    println!("There is 7 in the array: {}", find(7, &a));
4    println!("There is 8 in the array: {}", find(8, &a));
5}
6
7fn find(n: i32, a: &[i32]) -> bool {
8    for i in a {
9        if *i == n {
10          return true;
11        }
12    }
13
14    false
15}
16

find 函数接受一个 i32 类型 n 和一个 i32 类型的切片(slice)a ,返回一个 bool 值,若 n 是 a 的元素,则返回 ‘true’,否则返回 false。可以看到,return 关键字,用在 for 循环 if 表达式中,若此时 a 的元素与 n 相等,则立刻返回 true,剩下的循环不必再进行,否则一直循环检测完整个切片(slice),最后返回 false。

不过,return 语句也可以用在最后返回,把 find 函数最后一句 false 改为 return false; (注意分号不可以省略)也是可以的:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1fn main() {
2    let a = [1, 2, 3, 4, 8, 9];
3    println!("There is 7 in the array: {}", find(7, &a));
4    println!("There is 8 in the array: {}", find(8, &a));
5}
6
7fn find(n: i32, a: &[i32]) -> bool {
8    for i in a {
9        if *i == n {
10            return true;
11        }
12    }
13
14    return false;
15}
16

不过这是一个糟糕的风格,不是 Rust 的编程风格了。

需要注意的是,for 循环中的 i ,其类型为 &i32,需要使用解引用来变换为 i32 类型。切片(slice)可以看作是对数组的引用,后面的章节中会详细介绍切片(slice)。

返回多个值

Rust 函数不支持多个返回值,但是我们可以利用元组返回多个值,配合 Rust 的模式匹配,使用起来十分灵活。比如这个例子:


1
2
3
4
5
6
7
8
9
10
1fn mian() {
2    let (p2, p3) = pow_2_3(456);
3    println!("pow 2 of 456 is {}.", p2);
4    println!("pow 3 of 456 is {}.", p3);
5}
6
7fn pow_2_3(n: i32) -> (i32, i32) {
8    (n * n, n * n * n)
9}
10

这个例子中,pow_2_3 函数接收一个 i32 类型的值,返回其二次方和三次方的值,这两个数值包装再一个元组中返回。在 main 函数中,let 语句就可以使用模式匹配将函数返回的元组进行解构,将这两个返回值分别赋给 p2 和 p3, 从而可以得到 456 的二次方和三次方的值。

函数作为返回值

函数作为返回值,其声明与普通函数的返回类型申明一样:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1fn main() {
2    let a = [1,2,3,4,5,6,7];
3    let mut b = Vec::<i32>::new();
4    for i in &a {
5        b.push(get_func(*i)(*i));
6    }
7    println!("{:?}", b);
8}
9
10fn get_func(n: i32) -> fn(i32) -> i32 {
11    fn inc(n: i32) -> i32 {
12        n + 1
13    }
14    fn dec(n: i32) -> i32 {
15        n - 1
16    }
17    if n % 2 == 0 {
18        inc
19    } else {
20        dec
21    }
22}
23

这个例子中,get_func 函数接收一个 i32 类型的参数,返回一个类型为 fn(i32) -> i32 的函数,若传入的参数为偶数,返回 inc ,否则返回 dec。这里需要注意的是, inc 函数和 ‘dec’ 函数的定义在 get_func 内,在函数内定义函数在很多其他语言中是不支持的,不过 Rust 支持,这也是 Rust 灵活强大的体现。不过,在函数中定义的函数,不能包含函数中的变量,若要包含,应该使用闭包。所以:


1
2
3
4
5
6
7
8
9
10
11
12
13
1fn main() {
2    let f = get_func();
3    println!("{}", f(3));
4}
5
6fn get_func() -> fn(i32)->i32 {
7    let a = 1;
8    fn inc(n:i32) -> i32 {
9        n + a
10    }
11    inc
12}
13

这个例子会编译出错:


1
2
3
4
5
6
7
8
9
10
11
1  Compiling hello_world v0.1.0 (yourpath/hello_world)
2error[E0434]: can't capture dynamic environment in a fn item; use the || { ... } closure form instead
3 --> main.rs:9:9
4  |
59 |     n + a
6  |         ^
7
8error: aborting due to previous error
9
10error: Could not compile `hello_world`.
11

如果改成闭包的话是可以的:


1
2
3
4
5
6
7
8
9
10
11
1fn main() {
2    let f = get_func();
3    println!("{}", f(3));
4}
5
6fn get_func() -> Box<Fn(i32) -> i32> {
7    let a = 1;
8    let inc = move |n| n + a;
9    Box::new(inc)
10}
11

后续会详细介绍闭包。

发散函数

发散函数是 Rust 中的一个特性。发散函数并不返回,它使用感叹号 ! 作为返回类型表示。


1
2
3
4
1fn diverges() -> ! {
2    panic!("This function never returns!");
3}
4

panic!() 是一个宏,类似我们已经见过的 println!()。与 println!() 不同的是,panic!() 导致当前执行的线程崩溃并返回指定的信息。因为这个函数会崩溃,所以它不会返回,所以它拥有一个类型 !,它代表“发散”。

如果你添加一个叫做 diverges() 的函数并运行:


1
2
3
4
5
6
7
8
9
10
1fn main() {
2    println!("hello");
3    diverging();
4    println!("world");
5}
6
7fn diverging() -> ! {
8    panic!("This function will never return");
9}
10

由于发散函数不返回,所以就算其后再有其他语句也是不会执行的。如果后面还有其他语句,会出现以下编译警告:


1
2
3
4
5
6
7
8
9
1   Compiling hello_world v0.1.0 (yourpath/hello_world)
2warning: unreachable statement, #[warn(unreachable_code)] on by default
3 --> main.rs:4:3
4  |
54 |   println!("world");
6  |   ^^^^^^^^^^^^^^^^^^
7  |
8  = note: this error originates in a macro outside of the current crate
9

如果运行这个程序的化:


1
2
3
4
5
6
1     Running `yourpath\hello_world\target\debug\hello_world.exe`
2hello
3thread 'main' panicked at 'This function will never return', main.rs:8
4note: Run with `RUST_BACKTRACE=1` for a backtrace.
5error: process didn't exit successfully: `yourpath\hello_world\target\debug\hello_world.exe` (exit code: 101)
6

发散函数可以被用作任何类型:


1
2
3
4
5
6
1fn diverges() -> ! {
2    panic!("This function never returns!");
3}
4let x: i32 = diverges();
5let x: String = diverges();
6

函数指针

‘fn’ 关键字可以用来定义函数,除此之外,它还可以用来构造函数类型。与函数定义主要的不同是,构造函数类型不需要函数名、参数名和函数体。


1
2
3
4
5
6
7
8
9
10
11
1fn inc(n: i32) -> i32 {
2    n + 1
3}
4
5type IncType = fn(i32) -> i32;
6
7fn mian() {
8    let func: IncType = inc;
9    println!("3 + 1 = {}", func(3));
10}
11

这个例子中使用 ‘fn’ 定义了 inc 函数,它有一个 ‘i32’ 类型的参数,返回 i32 类型的值。然后再用 fn 定义了一个函数类型,这个函数类型有 i32 类型的参数和返回值,并用 type 关键字定义了它的别名 IncType。在 main 函数中定义了一个变量 func, 其类型为 IncType,并赋值为 inc 然后在 println 宏中调用:func(3)。可以看到,inc 函数的类型其实就是 IncType。

这里有一个问题,我们将 inc 赋值给了 func ,而不是 &inc ,这样将 inc 函数的所有权转移给了 func 吗?赋值后还可以以 inc() 形式调用 inc 函数吗?看这个例子:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1fn main() {
2    let func: IncType = inc;
3    println!("3 + 1 = {}", func(3));
4    println!("3 + 1 = {}", inc(3));
5}
6
7type IncType = fn(i32) -> i32;
8
9fn inc(n: i32) -> i32 {
10    n + 1
11}
12     Running `yourpath\hello_world\target\debug\hello_world`
133 + 1 = 4
143 + 1 = 4
15

这说明,赋值时, inc 函数的所有权并没有被转移到 func 变量上,而更像不可变引用。在 Rust 中,函数的所有权是不能转移的的,我们给函数类型的变量赋值是,赋给的一般是函数的指针,所以 Rust 中的函数类型,就像是 C/C++ 中的函数指针,当然, Rust 的函数类型更安全。可见,Rust 的函数类型,其实应该属于指针类型(Pointer Type)。Rust 中的指针类型有两种,一种为引用,另一种为原始指针。Rust 中的函数类型是引用类型,因为它是安全的,而原始指针是不安全的,要使用原始指针,必须使用 unsafe 关键字申明。

正因为函数类型属于指针类型,所以函数是可以作为数据在程序中进行传递。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1fn one(n: i32) -> i32 {
2    n + 1
3}
4
5fn two(n: i32) -> i32 {
6    n + 2
7}
8
9fn three(n: i32) -> i32 {
10    n + 3
11}
12
13fn main() {
14
15    let f1: fn(i32) -> i32 = one;
16    let f2: fn(i32) -> i32 = two;
17    let f3: fn(i32) -> i32 = three;
18
19    let funcs = [f1, f2, f3];
20
21    for f in &funcs {
22      println!("{:?}", f(1));
23    }
24}
25

我们将三个类型为 fn(i32) -> i32 的函数放到了一个数组中,并且去遍历执行。要注意 for f in &fnucs 这里,为什么要用引用呢?如果去掉 &:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1Compiling hello_world v0.1.0 (yourpath/hello_world)
2error[E0277]: the trait bound `[fn(i32) -> i32; 3]: std::iter::Iterator` is not satisfied
3  --> main.rs:21:5
4   |
521 |     for f in funcs {
6   |     ^ trait `[fn(i32) -> i32; 3]: std::iter::Iterator` not satisfied
7   |
8   = note: `[fn(i32) -> i32; 3]` is not an iterator; maybe try calling `.iter()` or a similar method
9   = note: required by `std::iter::IntoIterator::into_iter`
10
11error: aborting due to previous error
12
13error: Could not compile `hello_world`.
14

是因为数组没有实现 std::iter::Iterator 这个 trait, 而切片(Slices)是一个数组的引用,切片(Slices)是实现了 std::iter::Iterator 的。

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++异常

2022-1-11 12:36:11

安全经验

MySQL-查询优化

2021-11-28 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索