bhylu.com

Advertisements

Rust Data Types and Tuples

Choose representations that express a count and its unit.

How it works

Rust scalar types include integers, floating-point numbers, Boolean values and Unicode scalar characters. Tuples group a fixed set of possibly different types. Inference can choose a type from context, but public interfaces benefit from explicit types. A machine integer has a finite range; use checked operations when an external count might overflow.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

data-types.rs

fn main() {
    let record: (&str, u32, bool) = ("north", 8, true);
    let (area, count, ready) = record;
    assert!(ready);
    assert_eq!(count.checked_add(2), Some(10));
    println!("{area}: {count} packets");
}

Expected result

north: 8 packets

The tuple’s three positions have different meanings and types. Destructuring names them for the calculation. A struct is often clearer when several records share the same fields or when positions are easy to confuse. checked_add makes overflow part of the result instead of relying on build-profile behaviour.

Primary technical reference: Rust documentation.