Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ THE FIRST BUILD
BUILD NOTE 03 / 53

Give values the right shape.

Choose numeric types and handle arithmetic boundaries deliberately.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

Rust distinguishes signed integers such as i32, unsigned integers such as u64, and platform-sized usize values used for indexing. Floating-point values use f32 or f64 and cannot represent every decimal fraction exactly. A bool is true or false. A char is one Unicode scalar value, which can occupy more than one UTF-8 byte and is not necessarily an entire visible grapheme. Integer overflow behavior depends on build settings; checked arithmetic makes the boundary explicit in every build.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/scalar-types/src/main.rs
fn main() {
    let temperature: i32 = -4;
    let ready: bool = temperature < 0;
    let symbol: char = '🦀';
    let safe = u8::MAX.checked_add(1);
    println!("{temperature} {ready} {symbol}");
    println!("overflow: {safe:?}");
}
↳ EXPECTED OUTPUT
-4 true 🦀
overflow: None
  1. 1

    The signed integer can represent negative temperatures.

  2. 2

    checked_add returns None when the result would exceed u8.

  3. 3

    Debug formatting prints the Option variant.

From the extracted rust-workbench folder
cargo run -p lesson_scalar_types

03 Mind the boundary

04 Your next build

A SMALL MISSION

Use u8::try_from to reject 300, and checked_mul to detect overflow in 200_u8 * 2.

Reveal one possible solution +
solutions/scalar-types/src/main.rs
fn main() {
    assert!(u8::try_from(300).is_err());
    assert_eq!(200_u8.checked_mul(2), None);
    assert_eq!(12_u8.checked_mul(2), Some(24));
}

05 Check your reasoning

QUICK SIGNAL CHECK

Which type normally indexes a slice?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.