Variables and types

let and let mut, the number types, String and &str, constants, shadowing, and parsing text into numbers.

Runs in Zerethon IDE · Rust 1.87 Official Rust documentation ↗

Variables are immutable unless declared with mut. The type is usually inferred; write it after a colon when it is not (let n: i32 = ...).

main.rs
fn main() {
    let count: i32 = 3;
    let price = 9.5; // f64
    let name = String::from("Ada");
    let ready = true;
    let mut total = 0;
    total += count;
    total += 1;
    println!("{count} {price} {name} {ready} {total}");

    let parsed: i32 = "42".parse().unwrap();
    println!("{} {}", parsed + 1, count as f64 * price);
    println!("{} {} {} {}", 7 / 2, 7.0 / 2.0, 7 % 2, 2_i32.pow(10));

    const LIMIT: u32 = 10;
    let shadow = "5";
    let shadow: i32 = shadow.parse().unwrap();
    println!("{LIMIT} {shadow}");
}

Output

3 9.5 Ada true 4
43 28.5
3 3.5 1 1024
10 5
  • Integer types say their size: i32 (the default), i64, u8, usize (for indexes and lengths). Floats are f64 or f32.
  • Rust never converts number types for you: count * price with an i32 and an f64 does not compile — write count as f64 * price.
  • String is an owned, growable string; &str is a borrowed view of text, such as a literal "Ada".
  • "42".parse::<i32>() returns a Result; .unwrap() takes the number or stops the program if the text is not one.
  • Declaring a new variable with the same name (shadowing) is allowed and common when converting a value.

Watch out: Programs here are compiled with optimizations, so integer overflow is not checked: 255_u8 + 1 silently becomes 0. Use checked_add, saturating_add or a larger type when a value can grow.