๐ง Rust Primitive Data Types
Rust has scalar and compound types:
โ Scalar Types
Type | Description | Example Values |
---|---|---|
i8 ..i128 |
Signed integers (8โ128 bits) | -42 , 0 , 127 |
u8 ..u128 |
Unsigned integers (8โ128 bits) | 0 , 255 , 100 |
isize , usize |
Pointer-sized int types | Architecture dependent |
f32 , f64 |
Floating-point numbers | 3.14 , -2.0 |
bool |
Boolean | true , false |
char |
Unicode scalar value (4 bytes) | 'a' , 'โ' , '๐' |
Default types:
i32
for integers,f64
for floats,char
for characters.
๐ฆ Compound Types
1. Tuple
Fixed-size collection of values (can be of different types).
let tup: (i32, f64, char) = (42, 3.14, 'z');
let (x, y, z) = tup; // Destructuring
println!("{}", tup.0); // Access with index
2. Array
Fixed-size collection of values of the same type.
Arrays are stack-allocated and have fixed length.
๐ Type Inference and Annotation
Rust can infer types, but you can also explicitly specify:
let a = 10; // inferred as i32
let b: u64 = 20; // explicitly u64
let pi: f32 = 3.14;
let truth: bool = true;
๐งช Type Casting (Safe & Explicit)
Use as
for explicit casting:
No implicit casting between types (unlike C/C++). Always explicit!
๐ก Common Traits on Primitives
Trait | Use Case |
---|---|
Copy |
Duplicates value (no move) |
Clone |
Makes an explicit deep copy |
Debug |
Printable with {:?} |
Default |
Provides sensible default |
โ ๏ธ Overflow & Special Cases in Rust Primitives
๐น Integer Overflow
Mode | Behavior |
---|---|
Debug | โ Panic on overflow |
Release | โ Wrap around silently |
Example (Debug mode):
Example (Release mode):
๐น Safe Integer Operations
Method | Description |
---|---|
wrapping_add(x) |
Wraps around on overflow |
checked_add(x) |
Returns None if overflow occurs |
saturating_add(x) |
Clamps to max/min if overflow occurs |
overflowing_add(x) |
Returns (value, overflow: bool) |
let a: u8 = 250;
println!("{}", a.wrapping_add(10)); // โ 4
println!("{:?}", a.checked_add(10)); // โ None
println!("{}", a.saturating_add(10)); // โ 255
println!("{:?}", a.overflowing_add(10));// โ (4, true)
๐น Signed Integers
Signed integers (like i8
, i32
) overflow just like unsigned ones:
๐น Floating Point (f32, f64)
No panics, but:
Concept | Description |
---|---|
Overflow | Becomes inf or -inf |
Underflow | Becomes 0.0 or denormalized subnormal |
Division by zero | Becomes inf or NaN |
Invalid operations | Produce NaN |
let a = 1e308f64;
println!("{}", a * 10.0); // inf
let b = 0.0f64;
println!("{}", 1.0 / b); // inf
let c: f64 = 0.0 / 0.0;
println!("{}", c.is_nan()); // true
๐น Summary Table
Type | Panics on Overflow | Wraps | Special Values |
---|---|---|---|
u8 , i32 |
โ Debug mode | โ Release | - |
f32 , f64 |
โ Never panics | N/A | NaN , inf , -inf |