Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Numbers

Literals

  • Literal is a notation representing a fixed value in the code
  • You can use underscores in literals, i.e. 98222 is the same as 98_222
  • Type annotation for literal can be provided as a suffix, i.e. 23u32 is 23 that is explicitly typed as u32

Integer literals:

Number literalsExample
Decimal98_222
Hex0xff
Octal0o77
Binary0b1111_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 / 3 results in 1

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

LengthSignedUnsigned
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
Architecture-dependentisizeusize
  • signed can represent negative number whereas unsigned is always positive.
  • isize and usize depend 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::MIN or u8::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: f32 and f64, 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
}