Skip to the workspace
Pebellslearn by building
Language Basics  ›  Lesson

Integers, Floats, Booleans and Characters

Integers 12 minRust's scalar types are sized integers, two float sizes, bool and a four-byte Unicode char, and the compiler never converts between them silently.

rust / Integers, Floats, Booleans and Characters

Explore each scene at your own pace.

01 · The rule

The rule

Integers, Floats, Booleans and Characters

Rust's scalar types are sized integers, two float sizes, bool and a four-byte Unicode char, and the compiler never converts between them silently.

Choose scalar representations and inspect boundaries that affect arithmetic or text.

A book record in the library holds a page count, a star rating, whether it is out on loan, and a shelf letter. Each of those is a scalar: a single value. Rust makes you choose a precise type for each, and then holds you to it.

The rule

Sized numbers, true or false, one Unicode char, and no silent conversions.

Integers are named by sign and bit width: i8 i16 i32 i64 i128 (signed) and u8 u16 u32 u64 u128 (unsigned, never negative). isize and usize match the machine's pointer size; usize is the type for indexes and lengths. The default is i32.

let pages: u32 = 412;
let year: i32 = -350;       // signed, so negative is allowed
let big = 1_000_000;        // underscores just help reading

A u8 holds 0 to 255. Going past the limit is overflow: a debug build panics, a release build wraps around. When wrapping is what you want, say so with methods like wrapping_add, or use checked_add, which returns nothing on overflow.

Floats are f64 (default) and f32. let rating = 4.5; is an f64.

Booleans are bool: true or false.

Characters are char, written in single quotes. A char is four bytes and holds any Unicode scalar value, not just ASCII:

let shelf = 'F';
let mark = '✓';

No silent conversions. u32 + f64 does not compile. Convert on purpose with as:

let per_page = rating / pages as f64;
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.