Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust type mismatch in numerical operation

  • i32
  • i64
fn main() {
    let x: i32 = 3;
    let y: i64 = 7;

    let z = x + 1;
    assert_eq!(z, 4);
    println!("{z}");

    let z = y + 1;
    assert_eq!(z, 8);
    println!("{z}");

    //let z = x + y;
    //println!("{z}");
}
  • If we remove the i32 then this works even though the default is i32.
  • That's because Rust will infere the type of the first variable from the type of the second variable and the operation.