Type Inference

Rust will look at how the variable is used to determine the type:

  1. fn takes_u32(x: u32) {
  2. println!("u32: {x}");
  3. }
  4. fn takes_i8(y: i8) {
  5. println!("i8: {y}");
  6. }
  7. fn main() {
  8. let x = 10;
  9. let y = 20;
  10. takes_u32(x);
  11. takes_i8(y);
  12. // takes_u32(y);
  13. }

This slide demonstrates how the Rust compiler infers types based on constraints given by variable declarations and usages.

It is very important to emphasize that variables declared like this are not of some sort of dynamic “any type” that can hold any data. The machine code generated by such declaration is identical to the explicit declaration of a type. The compiler does the job for us and helps us write more concise code.

The following code tells the compiler to copy into a certain generic container without the code ever explicitly specifying the contained type, using _ as a placeholder:

  1. fn main() {
  2. let mut v = Vec::new();
  3. v.push((10, false));
  4. v.push((20, true));
  5. println!("v: {v:?}");
  6. let vv = v.iter().collect::<std::collections::HashSet<_>>();
  7. println!("vv: {vv:?}");
  8. }

collect relies on FromIterator, which HashSet implements.