Skip to content

03.函数

函数的声明

函数使用 fn 关键字声明。

函数的命名规范

rust 使用 snake case 命名规范:

  • 所有字母均为小写,单词之间使用下划线分隔

示例:

rust
fn main() {
    println!("Hello, world!");
    another_function();
}

fn another_function() {
    println!("this is another function");
}

NOTE

rust 中函数的声明位置不固定,不一定要求调用的位置在声明的位置之后,只要改函数可被调用,即可在任意位置声明,如上。

函数参数

函数的参数分为 2 种:parameters(形参)和 arguments(实参),其中,parameters 是声明函数时声明的参数,arguments 是在调用函数时传入的参数。

在声明形参时,必须给出参数的类型:

rust
fn main() {
    another_function(10);
}

fn another_function(x: i32) {
    println!("x is {}", x);
}

语句和表达式

rust 是基于表达式的语言。

语句不会返回值,表达式会返回值。

基于上述原理,不能将语句赋值,因为语句没有返回值。

每一行代码大部分都可以理解为一个语句,而语句中的某些数据可以理解为表达式,如 let a = 3; 中,3 就是表达式(字面值),整行代码 let a = 3; 就是语句;在 let a = 5 + 6; 中,5 + 6 就是表达式。

可以进行如下示例:

rust
let y = {
    let x = 1;
    x + 5
};
println!("y is {}", y)

由于 x + 5 没有以分号结尾,因此是一个表达式,产生返回值,为 6,因此,y 将获得返回值 6;如果在 x + 5 后面加上分号,则变为语句,语句没有返回值,因此 y 会报错:

rust
let y = {
    let x = 1;
    x + 5;
};
println!("y is {}", y)

编译时报错:

error[E0277]: `()` doesn't implement `std::fmt::Display`
 --> src\main.rs:8:25
  |
6 |         x + 5;
  |              - help: remove this semicolon
7 |     };
8 |     println!("y is {}", y)
  |                         ^ `()` cannot be formatted with the default formatter
  |
  = help: the trait `std::fmt::Display` is not implemented for `()`
  = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

如果函数没有最终的返回值,默认的返回值为一个空元组:()

函数返回值注解

和 Python 一样,使用箭头符号 -> 为函数的返回值指定类型:

rust
fn five() -> i32 {
    5  // 这里没有使用分号,是一个表达式,也是这个函数最终的返回值
}