Skip to content

Search

문서

Functions

Declaring and calling functions: typed parameters, return types, the last expression as the value, and recursion.

이 페이지의 내용

fn declares a function. Parameters always carry a type, and -> names what the function gives back.

pub fn area(w: float, h: float) -> float {
    w * h
}

// area(2.0, 3.5) == 7.0

The last expression of the body, with no ;, is the value. return leaves earlier.

pub fn clamp(v: int, lo: int, hi: int) -> int {
    if v < lo {
        return lo;
    }
    if v > hi {
        return hi;
    }
    v
}

// clamp(5, 0, 3) == 3
// clamp(-1, 0, 3) == 0

A function with no -> gives nothing back.

pub fn add_to(xs: [int], n: int) {
    xs.push(n);
}

What goes in

A number, a bool or a struct arrives as a copy, so changing it inside the function changes only the copy. A string, a list, a map and a class object arrive as the same thing the caller holds.

struct Wave { hp: int }

fn weaken(w: Wave) { w.hp = 0; }
fn extend(xs: [int]) { xs.push(9); }

pub fn run() -> str {
    let w = Wave { hp: 5 };
    let xs = [1];
    weaken(w);
    extend(xs);
    "{w.hp} {xs.len()}"
}

// run() == "5 2"

&mut parameters write back to the caller's own value.

Recursion and order

A function may call itself, and may call any function in the file, wherever it is declared. Recursion that runs out of stack traps.

pub fn fib(n: int) -> int {
    if n < 2 { n } else { fib(n - 1) + fib(n - 2) }
}

// fib(10) == 55

What is left out

  • One name is one function. A second fn of the same name is refused, so there is no overloading.
  • A parameter has no default, and every argument is given. Engine functions are the exception: their trailing optional arguments may be left out, as in log::recent(). balaur check warns about a last nil that could go, unless it is the only argument: node.set_script(nil) says what it does.
  • There are no variable arguments. A function that takes many values takes a list.
  • A function cannot sit inside another, and there are no closures.
fn f() -> int { 1 }
fn f() -> int { 2 }

// error: 2:1: `f` is defined twice

Function values cover passing a function to another one.