Rust is a statically typed language, which means the type of every variable is known at compile time. Most of the time, Rust can infer the type, so we don’t need an explicit declaration. But sometimes we do.
Scalar Types
Scalar types represent a single value. There are four primary scalar types: integers, floating-point numbers, booleans, and characters.
Integers
Integers come in different sizes. The main ones:
- Signed:
i8,i16,i32,i64,i128(can be negative) - Unsigned:
u8,u16,u32,u64,u128(only positive)
By default, Rust uses i32.
fn main() {
let x = 5; // ✅ i32 inferred
let y: u8 = 255; // ✅ explicitly u8
let z: i64 = 10; // ✅ explicitly i64
}An important note: if you try to store a value outside the range, you’ll get a compile error.
let num: u8 = 256; // ❌ Compile error (u8 max is 255)Floating-Point Numbers
Two floating-point types: f32 and f64 (default).
fn main() {
let x = 2.0; // ✅ f64 inferred
let y: f32 = 3.14; // ✅ explicitly f32
}Booleans
Pretty straightforward.
fn main() {
let t = true;
let f: bool = false;
}Characters
char represents a single Unicode character. Use single quotes, not double quotes.
fn main() {
let c = 'z';
let emoji = '😀'; // ✅ Works fine
}Compound Types
Compound types group multiple values into one type. The two primary ones: tuples and arrays.
Tuples
A fixed-length collection of values, potentially of different types.
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
// Destructuring
let (x, y, z) = tup;
println!("y: {}", y); // 6.4
// Or access by index
println!("First: {}", tup.0); // 500
}Tuples don’t have a length that can change. Once created, they’re fixed.
Arrays
A fixed-length collection of values with the same type.
fn main() {
let arr = [1, 2, 3, 4, 5]; // ✅ Inferred as [i32; 5]
let arr2: [i32; 5] = [1, 2, 3, 4, 5]; // ✅ Explicit
// Access by index
println!("First: {}", arr[0]); // 1
// Initialize with same value
let arr3 = [3; 5]; // [3, 3, 3, 3, 3]
}If you try to access an index that doesn’t exist, you’ll get a runtime panic. Rust catches this and prevents undefined behavior.
let arr = [1, 2, 3];
println!("{}", arr[10]); // ❌ Panic: index out of boundsTuples vs Arrays
Key difference:
- Tuples: Fixed length, can have different types. Use when you want to group different data.
- Arrays: Fixed length, same type. Use when all elements are the same type.
Think of tuples as a structured record, and arrays as a collection of the same thing.
That’s it for Day 3. Chapter 3 also covers functions, but that’s getting long, so it'll be in Day 4.
0 comments:
Post a Comment