Numbers
Literals
- Literal is a notation representing a fixed value in the code
- You can use underscores in literals, i.e.
98222is the same as98_222 - Type annotation for literal can be provided as a suffix, i.e.
23u32is23that is explicitly typed asu32
Integer literals:
| Number literals | Example |
|---|---|
| Decimal | 98_222 |
| Hex | 0xff |
| Octal | 0o77 |
| Binary | 0b1111_0000 |
| Byte (u8 only) | b’A’ |
Arithmetic operators
+for addition-for subtraction*for multiplication/for division%for remainder
Note:
- division of integer data types:
5 / 3results in1
No Automatic Type Coercion
- Rust is statically typed language (i.e. it must know the data type already during the compilation)
- Any conversion from one type to another has to be done explicitly
// this will produce compilation error
let b: u8 = 100;
let a: u32 = b;
// or this will produce compilation error
fn compute(a: u32, b: u32) -> u32 {
let multiplier: u8 = 4;
a + b * multiplier
}
Scalar Primitive Types
- represent a single value
Integer
| Length | Signed | Unsigned |
|---|---|---|
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| 128-bit | i128 | u128 |
| Architecture-dependent | isize | usize |
- signed can represent negative number whereas unsigned is always positive.
isizeandusizedepend on architecture: either 32-bit or 64-bit. (e.g. usage is when indexing a collection)- you can check the MAX or MIN value of each data type by using
u8::MINoru8::MAX:
fn main() {
let x = i8::MAX;
println!("The maximum value of data type i8 is {x}.");
}
Floating point number
- all floating point types are signed.
- Rust has two floating point types:
f32andf64, the latter one being default
fn main() {
let x = 3.2; // will default to f64
let y: f32 = 4.6; // is explicitly set to f32
}