Rust 函数

定义、返回值、参数、以及 `fn` 与闭包的分工。

Beginner
Key Points函数体最后一个表达式就是返回值,**不要加分号**。

定义与调用

Rust
fn greet(name: &str) -> String {
    format!("你好,{}", name)
}

fn main() {
    let msg = greet("Rust");
    println!("{}", msg);
}
Output
你好,Rust

Parameters must be typed and returns use ->. Rust does not infer types across function boundaries — deliberately, so the signature is a complete contract.

返回值

Rust
fn double(x: i32) -> i32 {
    x * 2               // 表达式,不加分号
}

fn double_explicit(x: i32) -> i32 {
    return x * 2;       // 也可以显式 return
}

fn nothing() {
    println!("没有返回值,实际返回 ()");
}

fn main() {
    println!("{} {}", double(3), double_explicit(4));
    nothing();
}
Output
6 8
没有返回值,实际返回 ()

return is for early exits. A trailing return x; works but is unidiomatic and clippy flags it as needless_return.

多返回值用元组

Rust
fn divmod(a: i32, b: i32) -> (i32, i32) {
    (a / b, a % b)
}

fn main() {
    let (q, r) = divmod(17, 5);
    println!("商 {} 余 {}", q, r);

    // 也可以直接取
    let t = divmod(10, 3);
    println!("{} {}", t.0, t.1);
}
Output
商 3 余 2
3 1

函数是一等公民

Rust
fn add(a: i32, b: i32) -> i32 { a + b }
fn sub(a: i32, b: i32) -> i32 { a - b }

fn apply(f: fn(i32, i32) -> i32, a: i32, b: i32) -> i32 {
    f(a, b)
}

fn main() {
    println!("{}", apply(add, 5, 3));
    println!("{}", apply(sub, 5, 3));

    // 存进 Vec
    let ops: Vec<fn(i32, i32) -> i32> = vec![add, sub];
    for op in ops {
        println!("{}", op(10, 4));
    }
}
Output
8
2
14
6

fn(i32, i32) -> i32 is a function pointer type — plain functions only. Closures that capture need a generic F: Fn(i32, i32) -> i32.

嵌套与作用域

Rust
fn main() {
    fn helper(x: i32) -> i32 {
        x + 1
    }

    println!("{}", helper(1));
}
Output
2

Functions may be nested but cannot capture outer variables — that is a closure's job. Nested functions mainly live in test modules or to keep a helper local.

impl Trait in return position is common: fn make() -> impl Iterator<Item = i32>. It hides the verbose type but allows only one concrete type.

Friends & Partners