Scalar types
Scalar types hold a single value: integers, floating-point numbers, booleans, and characters. They are fixed-size, live on the stack, and are copied rather than moved when assigned.
Detailed Explanation
Rust has four scalar families. Integers come in signed (i8, i16, i32, i64, i128) and unsigned (u8 through u128) widths, plus the pointer-sized pair usize and isize. Floats are f32 and f64. bool is true or false and occupies one byte. char is a single Unicode scalar value.
The defaults are i32 for integers and f64 for floats. When inference has nothing else to go on, those are what you get. i32 is chosen because it is fast on every target Rust supports and wide enough for most counting. Reach for a different width only when you have a reason: u8 for raw bytes, u64 for identifiers and timestamps, usize for anything that indexes or measures memory. Indexing a collection requires usize specifically, because usize is exactly as wide as a pointer on the target machine.
char deserves a moment, because it does not match C or Java. A Rust char is four bytes and holds one Unicode scalar value, so 'a', 'é', and '🦀' are each one char. It is not a byte, and it is not a UTF-16 code unit. A byte is u8. This is also why a String cannot be indexed by integer: bytes, chars, and what a human calls a character are three different counts.
Now the part that separates Rust from C. Integer overflow is defined behaviour, and what happens depends on the build profile.
- In a debug build, overflow panics:
attempt to add with overflow. - In a release build, overflow wraps using two's complement arithmetic.
Neither is undefined behaviour, so you never get the optimiser miscompiling around an overflow the way C's signed overflow allows. But the difference between profiles is real, and a bug that panics in your tests can silently produce a wrong number in production. The answer is to say what you mean, using the explicit method families:
| Family | Behaviour on overflow | Use when |
|---|---|---|
wrapping_add | Wraps around | Hashes, checksums, counters where wrapping is correct |
checked_add | Returns Option::None | You want to handle the failure |
saturating_add | Clamps to MAX or MIN | Clamped counters, timeouts, progress bars |
overflowing_add | Returns the wrapped value and a bool | You need both facts |
Every arithmetic operator has this family, not only addition.
Rust does no implicit numeric conversion at all. Adding a u8 to a u32 will not compile; you convert first. The safe conversion is From/Into, as in u32::from(small_byte), which exists only for conversions that cannot lose information. The unrestricted conversion is the as operator, and as truncates without complaint: 300i32 as u8 produces 44, and -1i32 as u32 produces 4294967295. Float to integer with as saturates rather than wrapping, and truncates toward zero. Prefer From when the conversion is lossless and TryFrom when it might not be; TryFrom returns a Result so the failure is visible. Use as when you have thought about the truncation and want it.
Floats follow IEEE 754 and carry the usual hazards: 0.1 + 0.2 != 0.3, and NaN is not equal to itself. Because of NaN, f64 implements PartialOrd but not Ord, which is why you cannot call .sort() on a Vec<f64> and must use sort_by with a comparison that handles NaN.
The cost of all this is a little friction. You write conversions that other languages perform silently. What you get back is that the silent conversions, which are a classic source of security bugs, are now visible in the source.
Code Examples
fn main() {
let count = 42; // inferred i32
let ratio = 0.5; // inferred f64
let ready: bool = true;
let crab: char = '🦀'; // one char, four bytes
println!("{}", crab.len_utf8()); // prints: 4 — bytes needed in a UTF-8 string
println!("{}", "🦀".len()); // prints: 4 — String::len counts bytes, not chars
println!("{}", "🦀".chars().count()); // prints: 1
// No implicit widening: this needs an explicit, lossless conversion.
let byte: u8 = 200;
let total: u32 = count as u32 + u32::from(byte);
println!("{total}"); // prints: 242
let _ = (ratio, ready);
}fn main() {
let big: u8 = 250;
// Debug build: `big + 10` panics with 'attempt to add with overflow'.
// Release build: it silently wraps to 4. Say what you mean instead:
println!("{}", big.wrapping_add(10)); // prints: 4
println!("{}", big.saturating_add(10)); // prints: 255
println!("{:?}", big.checked_add(10)); // prints: None
println!("{:?}", big.checked_add(5)); // prints: Some(255)
// `as` truncates silently. This is the conversion to be careful with.
println!("{}", 300i32 as u8); // prints: 44
println!("{}", -1i32 as u32); // prints: 4294967295
println!("{}", 3.99f64 as i32); // prints: 3 — truncates toward zero
// Floats are not exact, and NaN breaks the usual ordering rules.
println!("{}", 0.1 + 0.2 == 0.3); // prints: false
println!("{}", f64::NAN == f64::NAN); // prints: false
}Common Gotchas
Overflow panics in debug and wraps in release
the same expression behaves differently between `cargo run` and `cargo run --release`. Never rely on the panic as a safety net in production code; use `checked_*` or `saturating_*` where overflow is possible.
Indexing needs `usize`
`v[i]` where `i` is an `i32` gives `error[E0277]: the type 'Vec<T>' cannot be indexed by 'i32'`. Convert with `as usize`, or better, iterate instead of indexing.
`as` is a silent truncating cast
it never fails and never warns, so a `u64` identifier narrowed to `u32` corrupts data quietly. Use `u32::try_from(id)?` when the value might not fit.
`f64` has no `Ord`
because `NaN` compares unequal to everything, sorting floats requires `sort_by(|a, b| a.partial_cmp(b).unwrap())` or the `total_cmp` method. This is a deliberate refusal to paper over IEEE 754.