Rust Tutorial · Rust Basics · Lesson 5 of 29
Rust Data Types
Integers, floats, booleans, characters, tuples and arrays, and how Rust handles type conversion and overflow.
Scalar types
| Type | Examples |
|---|---|
| Integers | i8 i16 i32 i64 i128 isize, unsigned u8 ... u128 usize |
| Floats | f32, f64 (default) |
| Boolean | bool |
| Character | char (a Unicode scalar value, 4 bytes) |
Rust never converts types implicitly: use as for numeric casts, or From/TryFrom for checked conversions.
fn main() {
let count: u32 = 7;
let ratio = count as f64 / 2.0;
let letter: char = 'R';
let ok: bool = count > 5;
let small: u8 = u8::try_from(300_i32).unwrap_or(u8::MAX);
println!("{ratio} {letter} {ok} {small}");
let point = (3, -2);
let (x, y) = point;
let scores = [90, 85, 72];
println!("x={x} y={y} first={} len={}", scores[0], scores.len());
}
Output
3.5 R true 255 x=3 y=-2 first=90 len=3
Run this on your computer — see “Get Started” for setup.
Overflow
In debug builds integer overflow panics; in release builds it wraps. Say what you want explicitly with
checked_, wrapping_ or saturating_ methods:
fn main() {
let stock: u8 = 250;
println!("{:?}", stock.checked_add(10)); // None: would overflow
println!("{}", stock.saturating_add(10)); // 255
println!("{}", stock.wrapping_add(10)); // 4
}
Output
None 255 4
Run this on your computer — see “Get Started” for setup.
Tuples and arrays
A tuple groups values of different types: (String, u32). An array has a fixed length: [i32; 3].
Test yourself
How do you convert an i32 into an f64 in Rust?
Automaticallyx as f64f64(x)x.toFloat()
Show answer
Answer: x as f64