Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Integers, Floats, Booleans and Characters

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;

The shortcut

Pick a type by asking three questions in order: Can it be negative? Can it have a fraction? How big can it get?

Typing a book's loan counterStep 1 of 4
  1. Negative?

    A count of loans can never be below zero, so unsigned: a u type.

The trap is mixing types in one expression and expecting Rust to promote one side, as C or Python would. It will not; convert explicitly.

Drills

Answer fast — trust the rule.

quick drill

What is the largest value a u8 can hold?

quick drill

What type does let rating = 4.5; get with no annotation?

quick drill

Which line is a valid char?

quick drill

With pages: u32 and rating: f64, what happens to pages + rating?

quick drill

In a debug build, what happens when a u8 holding 255 has 1 added with +?

Remember

  • Integers are sized and signed or unsigned; defaults are i32 and f64; char is one Unicode value in single quotes.
  • Ask: negative? fraction? how big?
  • Trap: no automatic conversion between numeric types; use as.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainChoose the types for a book record

Pick a type for a book's page count, its average star rating, whether it is on loan, and the first letter of its shelf code. Then explain why let total = pages + rating; fails and how to fix it.