Rust Basics - Types and Data Structures
Rust Basics - Types and Data Structures
Rust's type system is one of its most powerful features. It catches bugs at compile time and enables zero-cost abstractions.
Scalar Types
Integers
let a: i32 = 42; // 32-bit signed
let b: u64 = 100; // 64-bit unsigned
let c = 0xff; // Hexadecimal (i32 by default)
let d = 0o77; // Octal
let e = 0b1111_0000; // Binary with visual separator
| Length | Signed | Unsigned |
|--------|--------|----------|
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| arch | isize| usize |
Floating-Point
let x = 2.0; // f64 (default)
let y: f32 = 3.0; // f32
Booleans and Characters
let t = true;
let c = 'z';
let heart = '❤'; // Unicode support
Compound Types
Tuples
let tup: (i32, f64, &str) = (500, 6.4, "hi");
let (x, y, z) = tup; // Destructuring
let five_hundred = tup.0; // Index access
Arrays
let a = [1, 2, 3, 4, 5];
let months = ["Jan", "Feb", "Mar"];
let b: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0]
let first = a[0];
String Types
This is often confusing for beginners:
String - Owned, mutable, heap-allocated
let mut s = String::from("hello");
s.push_str(", world!");
&str - String slice, borrowed
let s = "hello"; // &str (string literal)
let s2 = &String::from("hi")[0..2]; // Slice
When to use which?
- Use
&strfor function arguments (flexible) - Use
Stringwhen you need ownership/mutation
Collections
Vector (Vec)
let mut v = vec![1, 2, 3];
v.push(4);// Iterating
for i in &v {
println!("{}", i);
}
HashMap
use std::collections::HashMap;let mut scores = HashMap::new();
scores.insert("Alice", 100);
scores.insert("Bob", 85);
Slices
Slices reference a contiguous sequence of elements:
let s = String::from("hello world");
let hello = &s[0..5]; // String slice
let world = &s[6..11];let a = [1, 2, 3, 4, 5];
let slice = &a[1..3]; // Array slice: [2, 3]
Smart Pointers
Box
For heap allocation:
let b = Box::new(5);
Rc and Arc
Reference counting for shared ownership:
use std::rc::Rc;let data = Rc::new(String::from("shared"));
let data2 = Rc::clone(&data);
Summary Table
| Type | Stack | Heap | Growable | Use Case | |------|-------|------|----------|----------| | Array | Yes | No | No | Fixed size known at compile time | | Vec | Pointer | Yes | Yes | Dynamic collection | | String | Pointer | Yes | Yes | Growable text | | &str | Pointer | No | No | String views | | Box | Pointer | Yes | No | Heap allocation, recursive types |
Mastering these types is essential for idiomatic Rust code!