CodeBlanks Logo Icon CodeBlanks

Type inference

Learn type inference in closures and when explicit types are required.

Type inference

A closure's parameter and return types are inferred from the first use and then fixed:

let ikile = |x| x * 2;
println!("{}", ikile(5));       // x fixed as i32
// println!("{}", ikile(2.5));  // error: expected i32, found f64

Unlike a generic function, a closure works with a single type. Different types need separate closures or a generic function.

Explicit types

Types can be written explicitly for readability or to resolve ambiguity. If the return type is written, the body must be in braces:

let uzunluk = |s: &str| -> usize { s.chars().count() };
println!("{}", uzunluk("kitap"));   // 5

A closure's type is an anonymous type the compiler generates; even if two closures have the same signature, their types differ.

Practice Inference and explicit type

Write the type-inferred let ikile = |x| x * 2; and the explicitly typed let uzunluk = |s: &str| -> usize { s.chars().count() }; closures. Print the results of ikile(5) and uzunluk("kitap") separated by a space.

Starter code

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

Sample solution

main.rs
fn main() {
    let ikile = |x| x * 2;
    let uzunluk = |s: &str| -> usize { s.chars().count() };
    println!("{} {}", ikile(5), uzunluk("kitap"));
}

Expected output

10 5

Questions and answers

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

1 What happens if <code>let f = |x| x;</code> is never called?

  • x is assumed to be i32
  • It only warns
  • Compile error: the type of x can't be inferred Correct answer
  • f becomes generic

Explanation: Without a use there is no type information; in that case write the type explicitly: |x: i32| x.

2 Return type

Question
let uzunluk = |s: &str| ____ { s.chars().count() };
Answer
let uzunluk = |s: &str| -> usize { s.chars().count() };

Explanation: A closure's return type is written with -> and the body needs braces.

3 Code and result

Term Meaning
let f = |x| x * 2; f(5) 10
f(5); f(2.5) Type error
let f = |x| x; (never called) Inference error
|s: &str| -> usize { .. } Explicit types

All lessons in Intermediate