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 aref64orf32. - Rust never converts number types for you:
count * pricewith ani32and anf64does not compile — writecount as f64 * price. Stringis an owned, growable string;&stris a borrowed view of text, such as a literal"Ada"."42".parse::<i32>()returns aResult;.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.