Basic Data Types | Rust Fundamentals lesson | BraveProgrammer
Lesson 6 of 50
·rust
Basic Data Types
12 minutes
Course progress12%
Basic Data Types
Rust's type system is a cornerstone of its safety and performance. Every value has a definite type, known at compile time, enabling the compiler to make optimizations and prevent errors.
Scalar Types
Scalars represent single values:
Integers
Signed (can be negative):
i8, i16, i32, i64, i128: 8 to 128-bit signed integers
isize: Platform-dependent (32-bit on 32-bit systems, 64-bit on 64-bit)
Unsigned (non-negative only):
u8, u16, u32, u64, u128: 8 to 128-bit unsigned integers
usize: Platform-dependent
leta: i32 = -42; // Signed 32-bitletb: u8 = 255; // Unsigned 8-bit (max value)letc = 5; // Type inferred as i32letd = 1_000_000; // Underscores for readability
Note: char is single-quoted, String is double-quoted.
Compound Types
Tuples
Group multiple values of different types:
lettup: (i32, f64, u8) = (500, 6.4, 1);
// Destructuringlet (x, y, z) = tup;
println!(\"y = {}\", y); // 6.4
// Accessing by index
println!(\"First: {}\", tup.0); // 500
Arrays
Fixed-size collections of same type:
letarr: [i32; 3] = [1, 2, 3]; // Type and length specifiedletarr = [5; 3]; // [5, 5, 5]println!(\"First: {}\", arr[0]); // 1
// Arrays have fixed size known at compile time
let len = arr.len(); // 3
Compound Type Example
fnmain() {
// Tuple with mixed typesletperson: (String, i32, bool) = (
String::from(\"Alice\"),
30,
true
);
let (name, age, active) = person;
println!(\"{} is {} years old\", name, age);
// Array of numbers
let scores: [i32; 5] = [95, 87, 92, 88, 90];
let average = (scores.iter().sum::<i32>() as f64) / scores.len() as f64;
println!(\"Average: {}\", average);
}