Rust Foundations · 10 min · free with an account

Numbers

Lesson preview · about 30%

Choosing a number type records a promise about range and precision. Rust makes conversions explicit so that promise cannot change silently at an arithmetic boundary.

Core idea

Numeric conversions are explicit because ranges and precision differ.

Start with the idea

Integers and floating-point values model different kinds of information. A signed integer such as i32 can represent negative values; an unsigned type such as u8 uses its bits for nonnegative values. usize is the natural type for an index or collection length because it matches the platform’s address width. f64 represents a broad range of fractional values, but most decimal fractions are approximations in binary, so exact equality is often the wrong test for a measured quantity. None of these types is automatically better: start with what the domain means.

In the example, files is a length-like count, temperature is fractional, and mask is one byte of bit flags. Those annotations tell a reader why the three values should not be treated as interchangeable. Rust refuses to add unrelated numeric types without a conversion, which forces you to choose the result range and sign deliberately. Before adding a cast, ask whether negative values are possible, whether the result can exceed the smaller type, and whether rounding matters.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Basics