SyntaxStudy
Sign Up
Rust Data Types and Control Flow
Rust Beginner 1 min read

Data Types and Control Flow

Rust is a statically typed language, meaning every variable's type is known at compile time. Rust can usually infer types from context, so explicit annotations are only required when ambiguity exists. The scalar types are integers (`i8`–`i128`, `u8`–`u128`, `isize`, `usize`), floating-point numbers (`f32`, `f64`), Booleans (`bool`), and characters (`char`). Compound types include tuples and fixed-length arrays. Control flow in Rust uses `if`/`else if`/`else`, `loop`, `while`, and `for`. A distinctive feature is that `if` is an expression — it returns a value — which means you can use it on the right-hand side of a `let` binding. The `loop` keyword creates an infinite loop that can return a value via the `break` expression, making it useful as a retry mechanism or state machine. The `for` loop in Rust iterates over any type that implements the `Iterator` trait, which includes ranges (`1..10`, `1..=10`), arrays, slices, and most standard-library collections. Using iterators instead of index-based loops is idiomatic Rust: it is safer (no off-by-one errors), often more readable, and can be composed with adapter methods like `map`, `filter`, and `fold`.
Example
fn main() {
    // Integer and float types
    let x: i32 = -42;
    let y: f64 = 3.14;
    let big: u128 = 340_282_366_920_938_463_463_374_607_431_768_211_455;
    println!("x={x}  y={y}  u128_max≈{big}");

    // if as an expression
    let abs_x = if x < 0 { -x } else { x };
    println!("|{x}| = {abs_x}");

    // Tuple and array
    let point: (i32, i32) = (10, 20);
    let rgb: [u8; 3] = [255, 128, 0];
    println!("point = ({}, {})", point.0, point.1);
    println!("red channel = {}", rgb[0]);

    // loop with a return value
    let mut attempts = 0;
    let result = loop {
        attempts += 1;
        if attempts == 3 {
            break attempts * 10;
        }
    };
    println!("loop returned {result} after {attempts} attempts");

    // for with a range and iterator adapters
    let sum: i32 = (1..=100).filter(|n| n % 2 == 0).sum();
    println!("Sum of even numbers 1..=100 = {sum}");

    // while loop
    let mut n = 1u64;
    while n < 1_000 {
        n *= 2;
    }
    println!("First power of 2 >= 1000: {n}");
}