Expressions & Flow · 11 min · free with an account

Operators & Casting

Lesson preview · about 30%

Arithmetic in Rust is checked, and conversions are always written down.

Core idea

Rust never converts numeric types for you, and overflow is a decision you make by name.

Start with the idea

There is no implicit numeric promotion: adding a u8 to a u32 is a compile error until you convert. In a debug build an overflowing add panics rather than silently wrapping, and in release it wraps — which is why the standard library gives you checked_, wrapping_, and saturating_ variants to say which one you meant.

The example shows why an overflow policy must be explicit. A u8 can hold values from 0 through 255, so 250 + 10 does not fit. checked_add returns None rather than a number; wrapping_add cycles around to 4; saturating_add clamps at 255. These are three different product decisions. A count of completed tasks probably should not wrap from 255 to 4, while a circular sequence number may intentionally do so. Pick the behavior from the domain before choosing the method.

The later as cast illustrates another boundary. Converting 300_i32 to u8 with as keeps only the low eight bits, yielding 44.

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