Rust – Scalars
Scalar data types represent single values. There are four types of scalar data types: integers, floats, bools and chars.
Integers #
Remember: 1 byte = 8 bits.
| Length | Signed | Unsigned |
|---|---|---|
| 8-bits | i8 | u8 |
| 16 | i16 | u16 |
| 32 | i32 | u32 |
| 64 | i64 | u64 |
| 128 | i128 | u128 |
| arch | isize | Usize |
A signed integer means it can be positive or negative. Signed integers are stored using two’s complement representation and can range from \( -2^{n-1} \) to \( 2^{n-1}-1 \) inclusive, where \( n \) is the length in bits.
Unsigned integers only store positive numbers and can range from \( 0 \) to \( 2^{n-1}-1 \) inclusive.
Arch means it is dependent on the architecture of your computer. For example, if you have a 64-bit computer arch would be 64-bit sized. You want to use arch when indexing some sort of collection.
Using the rust defaults for integers is recommended. For integers this is an i32.
Warning: Integer overflows are possible. In production, integer overflows wrap back around. Numbers greater than the maximum wrap back to the minimum number and vice-versa.
Float #
There are two types of floats in Rust - f32 and f64. The default is an f64 and is represented according to the IEEE-754 standard.
Bool #
Boolean variables are stored using 1-byte.
Char #
Char variables are stored using 4-bytes and represent a unicode scalar value.
Extra: Integer Literals #
| num literal | example |
|---|---|
| Decimal | 98_222 |
| Hex | 0xff |
| Octal | 0o77 |
| Binary | 0b1111_0000 |
| Byte (u8 only) | b’A’ |