2.4 Data Types and Type Annotations

Rust requires that all variables have a well-defined type, which can often be inferred by the compiler.

2.4.1 Basic Data Types

  • Integers: i8, i16, i32, i64, i128, isize (signed); u8, u16, u32, u64, u128, usize (unsigned)
  • Floating-Point Numbers: f32, f64
  • Booleans: bool
  • Characters: char (4 bytes, Unicode scalar values)

2.4.2 Type Inference

fn main() {
    let x = 42; // x: i32 inferred
    let y = 3.14; // y: f64 inferred
    println!("x = {}, y = {}", x, y);
}

2.4.3 Explicit Type Annotation

fn main() {
    let x: u8 = 255;
    println!("x = {}", x);
}

2.4.4 Comparison with C

In C, you have similar basic types but with different sizes and naming conventions.

int x = 42;       // Typically 32 bits
float y = 3.14f;  // Single-precision floating point
char c = 'A';     // 1 byte

Note: Rust's integer types have explicit sizes, reducing ambiguity.