CodeBlanks Logo Icon CodeBlanks

Summary - Functions

Combine parameters, returns and expressions to build calculation functions.

Functions summary

fn name(param: Type) -> Return: parameter types are required, the return value is the last expression (without a semicolon), and return is used for early exits. if, match and blocks are value-producing expressions. Several values are returned with a tuple. Names are written in snake_case.

fn istatistik(s: &[i32]) -> (i32, f64) {
    let toplam: i32 = s.iter().sum();
    (toplam, toplam as f64 / s.len() as f64)
}

Functions as values

Functions can be assigned to a variable like a value or passed to another function; their type looks like fn(i32) -> i32:

fn ikiye(n: i32) -> i32 { n * 2 }
fn uygula(f: fn(i32) -> i32, x: i32) -> i32 { f(x) }

println!("{}", uygula(ikiye, 21));   // 42

Closures (anonymous functions) will make this idea even more powerful later.

Practice Statistics

Write the istatistik(s: &[i32]) -> (i32, f64) function above. Destructure with let (t, o) = istatistik(&[2, 4, 9]); and print println!("{t} {o}");.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn istatistik(s: &[i32]) -> (i32, f64) {
    let toplam: i32 = s.iter().sum();
    (toplam, toplam as f64 / s.len() as f64)
}

fn main() {
    let (t, o) = istatistik(&[2, 4, 9]);
    println!("{t} {o}");
}

Expected output

15 5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>istatistik(&amp;[2, 4, 9])</code> return?

  • (15, 5.0) Correct answer
  • (15, 5)
  • (5.0, 15)
  • 15

Explanation: The sum is 15 (i32) and the average 15 / 3 = 5.0 (f64); the tuple order matches the signature.

2 Function type

Question
fn uygula(f: ____, x: i32) -> i32 {
    f(x)
}
Answer
fn uygula(f: fn(i32) -> i32, x: i32) -> i32 {
    f(x)
}

Explanation: fn(i32) -> i32 is the type of a function taking an i32 and returning an i32.

3 Group summary

Term Meaning
fn Definition
-> T Return type
Last expression Return value
return Early exit

All lessons in Beginner