Inference

The type inference engine is pretty smart. It does more than looking at the type of the r-value 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:

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

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

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

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

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