| Integers (signed) |
i8, i16, i32, i64, i128, isize |
let x: i32 = -42; |
Signed integers (can be negative) |
| Integers (unsigned) |
u8, u16, u32, u64, u128, usize |
let y: u32 = 42; |
Unsigned integers (non-negative) |
| Floating point |
f32, f64 |
let pi: f64 = 3.1415; |
Decimal numbers |
| Boolean |
bool |
let is_ok = true; |
Logical true/false values |
| Character |
char |
let c = 'R'; |
Unicode scalar value (single character) |
| String slice |
&str |
let s = "hello"; |
Immutable view into a string literal |
| Owned string |
String |
let name = String::from("Souhaila"); |
Growable, heap-allocated string |
| Tuple |
(i32, f64, char) |
let t = (10, 3.14, 'x'); |
Fixed-size collection of mixed types |
| Array |
[T; N] |
let arr = [1, 2, 3]; |
Fixed-size list, all elements same type |
| Vector |
Vec<T> |
let v = vec![1, 2, 3]; |
Growable list (dynamic size) |
| Slice |
&[T] / &mut [T] |
let s = &v[1..3]; |
Borrowed view into array/vector |
| Struct |
struct Person { name: String, age: u8 } |
let p = Person { name: "A".into(), age: 30 }; |
Custom type grouping named fields |
| Enum |
enum Color { Red, Green, Blue } |
let c = Color::Red; |
Type with variants (sum type) |
| Option |
Option<T> |
let maybe = Some(10); |
Represents optional value (Some or None) |
| Result |
Result<T, E> |
let r: Result<i32, &str> = Ok(5); |
Used for error handling (Ok or Err) |
| Range |
Range<T> |
for i in 0..5 {} |
Represents a sequence of values |
| Reference |
&T |
let r = &x; |
Immutable reference (borrow) |
| Mutable reference |
&mut T |
let r = &mut x; |
Mutable borrow |
| Constant |
const |
const PI: f64 = 3.14; |
Immutable compile-time constant |
| Static variable |
static |
static MAX: i32 = 100; |
Global variable (lives for entire program) |
| HashMap |
HashMap<K, V> |
use std::collections::HashMap; |
Key-value store (like a dictionary) |
| HashSet |
HashSet<T> |
use std::collections::HashSet; |
Unordered collection of unique values |
| Box |
Box<T> |
let b = Box::new(5); |
Heap-allocated value (smart pointer) |
| Rc |
Rc<T> |
use std::rc::Rc; |
Reference-counted shared ownership |
| Arc |
Arc<T> |
use std::sync::Arc; |
Thread-safe reference-counted pointer |
| Unit type |
() |
let x = (); |
Empty value or “nothing returned” |
| Function pointer |
fn(T) -> U |
fn add(x: i32) -> i32 { x + 1 } |
Reference to a function |
| Closure |
` |
x |
x + 1` |
`let f = |
x |
x * 2;` |
Anonymous function that can capture variables |