OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Numbers and explicit conversion

Use integer types deliberately and handle failed parsing or arithmetic.

Lesson 4 of 30 · About 20 minutes · Beginner · English

By the end of this lesson

Use integer types deliberately and handle failed parsing or arithmetic.

Before you start

  • Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
  • Complete lesson 3, or be comfortable explaining and running its examples.

Three words to know

Integer
A whole number in a finite range.
Parse
Convert text according to a type’s grammar.
Checked arithmetic
An operation reporting overflow instead of assuming it cannot happen.

1. Understand the idea

Rust does not silently combine every numeric type. Write an explicit type when the range matters. Text input is not already a number: parse returns Result because it can fail. A numeric type has limits; checked_add returns None when a sum would not fit. Debug and optimized builds can behave differently for unchecked overflowing arithmetic, so use an explicit policy.

2. Save, run and observe

Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.

Parse and add safelyRUST · save as lesson.rs
fn main() {
    let pages: u16 = "12".parse().expect("fixed example is numeric");
    println!("pages={pages}");
    println!("fits={}", u8::MAX.checked_add(1).is_some());
}
What you should see · example output
pages=12
fits=false
Compile and run on macOS/LinuxTERMINAL · Bash or Windows PowerShell
rustc --edition=2024 lesson.rs -o lesson
./lesson

3. Explain the result

Here expect documents an assumption about a fixed literal, not a good general input policy. pages is an unsigned 16-bit integer. u8::MAX is 255 and adding one does not fit in u8, so checked_add returns None. Later we will use Result to report invalid user input without a panic.

YOUR TURN

A small check before you continue

What should a user-facing program do if parsing 12pages as u16 fails?

Show a suggested answer

Return or handle the error, rather than call expect on untrusted input. Rust does not parse only the numeric prefix here.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.