typestar

Functions in Rust

Defining, composing, and passing functions.

fn square(x: i32) -> i32 {
    x * x
}

fn sum_of_squares(a: i32, b: i32) -> i32 {
    square(a) + square(b)
}

fn main() {
    let result = sum_of_squares(3, 4);
    let apply = |f: fn(i32) -> i32, v| f(v);
    let squared = apply(square, 5);
    println!("{result} {squared}");
}

How it works

  1. The last expression is returned without return.
  2. sum_of_squares calls square twice.
  3. A fn pointer can be passed to a closure.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
257
Tokens
91
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 1 of 4 in Functions, step 23 of 39 in Language basics.

← Previous Next →

Functions in other languages