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
- The last expression is returned without
return. sum_of_squarescallssquaretwice.- A
fnpointer can be passed to a closure.
Keywords and builtins used here
fni32letmainsquaresum_of_squares
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.
Step 1 of 4 in Functions, step 23 of 39 in Language basics.