Common programming concepts
Data types
There are two kinds of types: scalar and compound. Scalar types are types that are not “containers” and represent a single value, like integers, floating point numbers, and characters.
Rust has four primitive scalar types: integers, floating-point numbers,
Booleans, and characters. Rust’s integers can be signed or unsigned and signed
integers are stored in two’s complement form. Rust’s default integer type is
i32. isize or usize change depending on the computer’s architecture.
Rust handles integer overflow differently depending on context. If you assign a variable with a value outside of the type’s range, the compiler will panic at runtime in debug mode. In release mode, the compiler will do two’s complement wrapping.
You can use any of these functions to check for overflow:
- Wrap in all modes with the wrapping_* methods, such as wrapping_add
- Return the None value if there is overflow with the checked_* methods
- Return the value and a boolean indicating whether there was overflow with the overflowing_* methods
- Saturate at the value’s minimum or maximum values with saturating_* methods
On a related note, out-of-bounds indexing is checked at runtime. Instead of possibly accessing invalid memory, Rust panics before accessing the invalid index.
let x: i64 = 4;
let y: u8 = 4;
let z: usize = 8_000;
let a = 0b00_11;
// this is a byte and is u8
let b = b'B';