Rust Type Inference Advanced Example

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, the type inference engine is highlighted for its ability to deduce the type of a variable based on its usage and value assignment, demonstrated in an advanced example using Rust programming language.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.

Inference

The type inference engine is pretty smart. It does more than looking at the type of the value expression during an initialization. It also looks at how the variable is used afterwards to infer its type. Here's an advanced example of type inference:

fn main() {
    // Because of the annotation, the compiler knows that `elem` has type u8.
    let elem = 5u8;

    // Create an empty vector (a growable array).
    let mut vec = Vec::new();
    // At this point the compiler doesn't know the exact type of `vec`, it
    // just knows that it's a vector of something (`Vec<_>`).

    // Insert `elem` in the vector.
    vec.push(elem);
    // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec<u8>`)
    // TODO ^ Try commenting out the `vec.push(elem)` line

    println!("{:?}", vec);
}

No type annotation of variables was needed, the compiler is happy and so is the programmer!

Summary

Congratulations! You have completed the Inference lab. You can practice more labs in LabEx to improve your skills.