Data Types
Rust has several different data types that you'll use frequently. The scalar types include integers like i32 (signed) and u32 (unsigned), floating-point numbers (f64 by default), booleans, and characters. Rust is statically typed, so it needs to know the types of all variables at compile time.
There are also compound types that can hold multiple values. Tuples can contain different types and have a fixed length. Arrays, on the other hand, must contain the same type and also have a fixed length. You can destructure tuples to access their individual elements.
When working with arrays, you access elements using indexing starting from 0. Slices let you reference a contiguous sequence of elements rather than the whole array. Rust will also check for array bounds at runtime, which helps prevent buffer overflow vulnerabilities.
fn main() {
// Scalar types
let integer: i32 = 42;
let unsigned: u32 = 42;
let float: f64 = 3.14;
let boolean: bool = true;
let character: char = 'A';
println!("Integer: {}", integer);
println!("Unsigned: {}", unsigned);
println!("Float: {}", float);
println!("Boolean: {}", boolean);
println!("Character: {}", character);
// Tuple - can hold different types
let tup: (i32, f64, bool) = (500, 6.4, true);
let (x, y, z) = tup; // Destructuring
println!("Tuple values: {}, {}, {}", x, y, z);
// Array - must be same type
let arr = [1, 2, 3, 4, 5];
let first = arr[0]; // Indexing
println!("First element: {}", first);
// Slice
let slice = &arr[1..3]; // Elements 1 and 2
println!("Slice: {:?}", slice);
}
Try it Yourself ->