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;
  4. // Create an empty vector (a growable array).
  5. let mut vec = Vec::new();
  6. // At this point the compiler doesn't know the exact type of `vec`, it
  7. // just knows that it's a vector of something (`Vec<_>`).
  8. // Insert `elem` in the vector.
  9. vec.push(elem);
  10. // Aha! Now the compiler knows that `vec` is a vector of `u8`s (`Vec<u8>`)
  11. // TODO ^ Try commenting out the `vec.push(elem)` line
  12. println!("{:?}", vec);
  13. }

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