Lesson 3
Data Types
Explore Rust's type system: integers, floats, booleans, characters, strings, tuples, and arrays.
Scalar Types
Rust has four primary scalar types: integers (i32, u64, etc.), floating-point numbers (f32, f64), booleans (bool), and characters (char). Integer types come in signed (i) and unsigned (u) variants with sizes from 8 to 128 bits. The default integer is i32.
Strings
Rust has two main string types: &str (a string slice, usually a literal) and String (a growable, heap-allocated string). You'll use both constantly. For now, just know that string literals like "hello" are &str.
Compound Types
Tuples group different types together with a fixed length: let point = (3, 4.5). Access elements with a dot and index: point.0. Arrays hold multiple values of the same type with a fixed length: let nums = [1, 2, 3]. Access elements with brackets: nums[0].
Run the code to see each type in action.
Try it
fn main() {
// Integers
let age: u32 = 30;
let temperature: i32 = -5;
println!("Age: {}, Temperature: {}", age, temperature);
// Floating point
let pi: f64 = 3.14159;
println!("Pi is approximately {}", pi);
// Boolean
let is_rust_fun: bool = true;
println!("Is Rust fun? {}", is_rust_fun);
// Character (supports Unicode!)
let letter: char = 'R';
let star: char = '*';
println!("Letter: {}, Star: {}", letter, star);
// String slice and String
let greeting: &str = "Hello";
let name: String = String::from("World");
println!("{}, {}!", greeting, name);
// Tuple: mixed types, fixed size
let person: (&str, i32, bool) = ("Alice", 28, true);
println!("Name: {}, Age: {}, Active: {}", person.0, person.1, person.2);
// Array: same type, fixed size
let colors = ["red", "green", "blue"];
println!("First color: {}", colors[0]);
println!("Array has {} elements", colors.len());
}Challenge
Create a tuple with your name, your age, and your favorite number. Print each element on its own line.
Previous: Variables & Mutability
Next: Functions