Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 1 · Fundamentals

    1.2Primitive & compound types

    Rust's sized integer and float types, 4-byte chars, tuples and fixed-size arrays, and why every numeric conversion is written out.

    About 20 minutesBeginner

    On this page
    1. Concept map
    2. Integers: the size is in the name
    3. Floats, booleans and characters
    4. Tuples and arrays
    5. Conversions are always explicit
    6. Which one should I use?
    7. Under the hood
    8. Common pitfalls
    9. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Whole numbersnumber (exact up to 2^53 − 1), or bigintint, long, byte, short, uint, ...i32, i64, u8, i16, u32, ...: the size is in the name
    Fractional numbersnumber (64-bit float)double, float, decimalf64, f32; no decimal in the standard library
    One characterNo type; a one-character stringchar: one UTF-16 code unit (2 bytes)char: one Unicode scalar value (4 bytes)
    A fixed group of valuesTuple [string, number]Tuple (string, int)Tuple (&str, i32), read with .0, .1
    A fixed-length listNo exact equivalent: number[] can always growint[]: fixed length, but the length isn't part of the type[i32; 3]: the length is part of the type
    int to longNothing to convertImplicit wideningAlways explicit: i64::from(n) or n as i64

    TypeScript has one number type for everything (plus bigint). Rust has a family of them, and the size and sign are part of each name.C# has a family of number types, and Rust’s are close to C#‘s, with one difference that matters every day: the size and sign are part of the name. i32 is a signed 32-bit integer, u8 is an unsigned 8-bit one. Rust also never converts between them for you, so every widening, narrowing and int-to-float step is written in the code.

    Integers: the size is in the name

    RustSizeRangeClosest in your language
    i8 / u81 byte−128 to 127 / 0 to 255numbersbyte / byte
    i16 / u162 bytesabout ±32 thousand / 0 to 65,535numbershort / ushort
    i32 / u324 bytesabout ±2.1 billion / 0 to 4.2 billionnumberint / uint
    i64 / u648 bytesabout ±9.2 × 10^18 / 0 to 1.8 × 10^19bigint past 2^53 − 1long / ulong
    i128 / u12816 bytesabout ±1.7 × 10^38 / 0 to 3.4 × 10^38bigintInt128 / UInt128
    isize / usizepointer size (8 bytes on 64-bit)depends on the machinenumbernint / nuint

    i means signed (can be negative), u means unsigned. A whole-number literal with nothing else to go on is an i32, just as C# picks int.

    TypeScript
    types.ts
    const score = 42;
    const bytesSent = 5_000_000_000;
    const red = 255;
    const names = ["Ada", "Grace", "Linus"];
    console.log(`${score} ${bytesSent} ${red} ${names.length}`);
    C#
    Types.cs
    int score = 42;
    long bytesSent = 5_000_000_000;
    byte red = 255;
    string[] names = ["Ada", "Grace", "Linus"];
    Console.WriteLine($"{score} {bytesSent} {red} {names.Length}");
    Rust
    let score = 42; // i32: the default
    let bytes_sent: u64 = 5_000_000_000; // too big for i32
    let red: u8 = 255;
    let names = ["Ada", "Grace", "Linus"];
    let count: usize = names.len(); // lengths and indexes are usize
    println!("{score} {bytes_sent} {red} {count}");

    Output

    42 5000000000 255 3

    Two things to notice in the Rust version. bytes_sent needs its type: without it, 5_000_000_000 would be an i32, and Rust refuses to compile a literal that doesn’t fit its type. And len() returns a usize, the unsigned, pointer-sized type Rust uses for every length and index. You’ll see usize everywhere you’d see number for .length in TypeScript.You’ll see usize everywhere you’d see int for .Count or .Length in C#.

    Floats, booleans and characters

    f64 is the same 64-bit IEEE 754 float as TypeScript’s numberC#‘s double, and it’s the default for a literal like 0.5. f32 is a 32-bit float, the kind a Float32Array holds.f32 matches C#‘s float. bool is true or false, and nothing else converts to it: there’s no truthy 0 or empty string.

    char is where Rust differs. TypeScript has no character type at all: one character is just a one-character string.A C# char is one UTF-16 code unit, 2 bytes, so an emoji doesn’t fit in one. A Rust char is 4 bytes and holds any Unicode scalar value, emoji included:

    TypeScript
    crab.ts
    const crab = "🦀";
    const chars = [...crab].length;
    const utf16Units = crab.length;
    const utf8Bytes = new TextEncoder().encode(crab).length;
    console.log(`${chars} char, ${utf16Units} UTF-16 units, ${utf8Bytes} UTF-8 bytes`);
    C#
    Crab.cs
    var crab = "🦀"; // a string: the crab doesn't fit in a C# char
    var chars = crab.EnumerateRunes().Count();
    var utf16Units = crab.Length;
    var utf8Bytes = System.Text.Encoding.UTF8.GetByteCount(crab);
    Console.WriteLine($"{chars} char, {utf16Units} UTF-16 units, {utf8Bytes} UTF-8 bytes");
    Rust
    let crab = '🦀'; // one char: single quotes
    let chars = crab.to_string().chars().count();
    let utf16_units = crab.len_utf16();
    let utf8_bytes = crab.len_utf8();
    println!("{chars} char, {utf16_units} UTF-16 units, {utf8_bytes} UTF-8 bytes");

    Output

    1 char, 2 UTF-16 units, 4 UTF-8 bytes

    Single quotes make a char, double quotes make a string. In Rust they aren’t interchangeable as they are in TypeScript, just as in C#.

    Tuples and arrays

    A tuple groups a fixed number of values that can have different types. An array holds a fixed number of values of one type, and its length is part of its type: [i32; 3] and [i32; 4] are different types.

    TypeScript
    point.ts
    const point: [number, number] = [3, 4];
    const [x, y] = point;
    const scores: number[] = [90, 85, 77];
    console.log(`${x} ${y} ${point[0]} ${scores.length} ${scores[0]}`);
    C#
    Point.cs
    (int X, int Y) point = (3, 4);
    var (x, y) = point;
    int[] scores = [90, 85, 77];
    Console.WriteLine($"{x} {y} {point.X} {scores.Length} {scores[0]}");
    Rust
    let point: (i32, i32) = (3, 4);
    let (x, y) = point;
    let scores: [i32; 3] = [90, 85, 77];
    println!("{x} {y} {} {} {}", point.0, scores.len(), scores[0]);

    Output

    3 4 3 3 90

    Tuple fields are read by position: point.0, point.1. An array can’t grow; when you need a list that changes size, use Vec<T> (Module 8). [0; 5] is a shorthand for five zeros.

    The empty tuple () has a name, unit. It’s what a function returns when it returns nothing: the next lesson, Functions, expressions & statements, covers it.

    Conversions are always explicit

    TypeScript never converts numbers because it has only number. Rust has many number types and never converts between them silently.C# widens an int to a long for you, and casts the other way with (byte)n. Rust does neither silently. You pick one of three tools:

    • i64::from(n) (or n.into()): only exists when the conversion can never lose data.
    • u8::try_from(n): for conversions that might not fit. It returns a Result: Ok with the value, or Err if it doesn’t fit.
    • n as u8: a raw cast that always succeeds. When narrowing, it keeps the low bits, so 300 as u8 is 44.
    TypeScript
    convert.ts
    const small = 200;
    const wide = small; // one number type: nothing to convert
    const tooBig = 300;
    const truncated = tooBig & 0xff; // keep the low 8 bits by hand
    const fits = tooBig >= 0 && tooBig <= 255;
    console.log(`${wide} ${truncated} ${fits}`);
    C#
    Convert.cs
    int small = 200;
    long wide = small; // implicit widening
    int tooBig = 300;
    byte truncated = (byte)tooBig; // keeps the low 8 bits
    bool fits = tooBig is >= byte.MinValue and <= byte.MaxValue;
    Console.WriteLine($"{wide} {truncated} {(fits ? "true" : "false")}");
    Rust
    let small: i32 = 200;
    let wide = i64::from(small); // lossless: always works
    let too_big: i32 = 300;
    let truncated = too_big as u8; // keeps the low 8 bits
    let fits = u8::try_from(too_big).is_ok(); // checks first
    println!("{wide} {truncated} {fits}");

    Output

    200 44 false

    Mental model shiftNo implicit numeric conversions

    Rust won’t even add an i32 to an i64, or an integer to a float, without a conversion. It feels noisy at first, but every place a value could change size is visible in the code. Prefer From and try_from over as: they can’t silently cut off data.

    Which one should I use?

    Picking a number size is new if you come from TypeScript.You already pick an integer width in C#, so the habits mostly carry over. Here’s the whole decision:

    WhatWhenWhyHow
    i32The default for whole numbers: counts, scores, ages, anything that might be negative.It’s what an unannotated literal becomes, and it’s fast on every CPU.let score = 42;
    usizeIndexes, lengths, sizes of collections.len() returns it and indexing takes it, so using it avoids conversions.let count = names.len();
    u8Raw bytes: file contents, network data, color channels.&[u8] is Rust’s binary data, like TypeScript’s Uint8ArrayC#‘s byte[].let red: u8 = 255;
    i64 / u64Values that can pass 2 billion: IDs, timestamps in milliseconds, file sizes.i32 tops out at 2,147,483,647.let bytes_sent: u64 = 5_000_000_000;
    i128 / u128Rarely: values beyond 64 bits, such as some IDs or hashes.Slower on most CPUs than 64-bit math.let id: u128 = 1 << 100;
    f64The default for fractional numbers.Same as TypeScript’s numberC#‘s double.let ratio = 0.75;
    f32Graphics, games, machine learning: large arrays of floats.Half the memory, less precision.let x: f32 = 0.5;
    MoneyPrices, balances, anything that must add up to the exact centC# would store in decimal.Floats can’t store 0.1 exactly, and std has no decimal.Integer cents in an i64, or a decimal crate such as rust_decimal.
    TupleA few values of different types that travel together, such as returning two values.No struct to declare.let point = (3, 4); then point.0
    Array [T; N]A list whose length never changes and is known when you write the code.Lives inline, with no heap allocation.let scores = [90, 85, 77]; For a list that grows, use Vec<T>.

    Rule of thumb: let the compiler infer i32 and f64, use usize for anything that counts or indexes a collection, u8 for bytes, and i64 or u64 as soon as a value could pass 2 billion. Never use floats for money. When you convert, use From for widening and try_from for narrowing; reach for as only when cutting off bits is what you want.

    Under the hood

    Every primitive, tuple and array has a size known at compile time, so Rust stores it inline: on the stack for a local variable, or directly inside whatever contains it. A TypeScript array is a heap object you reach through a reference.A C# int[] is a heap object you reach through a reference. A Rust [i32; 3] is just 12 bytes in place.

    use std::mem::size_of;
    println!("bool: {} byte", size_of::<bool>());
    println!("char: {} bytes", size_of::<char>());
    println!("i32: {} bytes", size_of::<i32>());
    println!("f64: {} bytes", size_of::<f64>());
    println!("usize: {} bytes", size_of::<usize>());
    println!("(i32, i32): {} bytes", size_of::<(i32, i32)>());
    println!("[i32; 3]: {} bytes", size_of::<[i32; 3]>());
    println!("(u8, u32): {} bytes", size_of::<(u8, u32)>());

    Laid out byte by byte, a tuple or an array is just its elements side by side. The last row shows one surprise: a tuple can be bigger than its parts add up to. A u32 has to sit at an address that’s a multiple of 4, so the compiler leaves 3 unused bytes of padding after the u8, and (u8, u32) takes 8 bytes, not 5.

    Sizes in bytes, today on a 64-bit target
    Sizes in bytes, today on a 64-bit target: each row is one value; each cell's width is its size in bytes.
    Value01234567891011Size
    boolbool1 byte1 bytes
    charchar4 bytes4 bytes
    i32i324 bytes4 bytes
    f64f648 bytes8 bytes
    usizeusize8 bytes8 bytes
    (i32, i32).0: i324 bytes.1: i324 bytes8 bytes
    [i32; 3][0]4 bytes[1]4 bytes[2]4 bytes12 bytes
    (u8, u32).01 bytepadding3 bytes.1: u324 bytes8 bytes

    Each row is one type, and each cell is as wide as its size in bytes. bool takes 1 byte, char and i32 take 4 bytes each, and f64 and usize take 8 bytes. The tuple (i32, i32) is its two 4-byte fields side by side, 8 bytes. The array [i32; 3] is three 4-byte elements side by side, 12 bytes, with nothing else stored. The tuple (u8, u32) holds its 1-byte u8, then 3 bytes of padding, then its 4-byte u32: 8 bytes in total. Primitive sizes are fixed by the language; usize is 8 bytes on a 64-bit target, and the order and padding of tuple fields are what the compiler does today, not a guarantee.

    let point: (i32, i32) = (3, 4);
    let scores: [i32; 3] = [90, 85, 77];
    println!("{} {}", point.0, scores[2]);
    A tuple and an array, stored inlineOn the stack, point is a tuple of two i32 fields holding 3 and 4, and scores is an array of three i32 elements holding 90, 85 and 77. Neither has a pointer to the heap: all the values sit directly in the variables.Stackpoint: (i32, i32).03.14scores: [i32; 3][0]90[1]85[2]77
    A tuple and an array, stored inline. On the stack, point is a tuple of two i32 fields holding 3 and 4, and scores is an array of three i32 elements holding 90, 85 and 77. Neither has a pointer to the heap: all the values sit directly in the variables.

    Because the array is the data itself, let copy = scores; copies all 12 bytes, and both arrays stay usable. That’s the Copy behavior from Copy vs. Clone: arrays and tuples of Copy types are Copy too.

    Common pitfalls

    Common pitfallOverflow panics in debug builds and wraps in release

    TypeScript’s number never wraps around; past 2^53 − 1 it silently loses precision instead.C# integer math wraps around silently unless you write checked. Rust checks: in a debug build (cargo run), adding 1 to a u8 that holds 255 stops the program with attempt to add with overflow. In a release build (cargo run --release) the check is off and the value wraps to 0. If the overflow is visible at compile time, for example two constants added together, the compiler rejects the code instead.

    Don’t rely on either behavior. When a value can overflow, say what you want:

    let level: u8 = 250;
    let bonus: u8 = 10;
    println!("{:?}", level.checked_add(bonus)); // None: tells you it didn't fit
    println!("{}", level.wrapping_add(bonus)); // 4: wraps around
    println!("{}", level.saturating_add(bonus)); // 255: stops at the maximum

    checked_* returns an Option: Some(value), or None on overflow. Use it when overflow means bad input. Use saturating_* for things like health bars and volume, and wrapping_* for hashes and checksums. wrapping_* is what C# does by default, outside a checked block.

    Common pitfallas can silently change a value

    as never fails: 300 as u8 is 44, -1i32 as u32 is 4294967295, and 3.99_f64 as i32 is 3. Float-to-integer casts drop the fraction and clamp to the target’s range instead of keeping low bits: 300.0_f64 as u8 is 255. That’s fine when you mean it, and a bug when you don’t. Use u8::try_from(n) when the value might not fit, and handle the error.

    Common pitfallYou can't mix number types in one expression

    let total = count + bytes; with an i32 and an i64 doesn’t compile: there’s no i32 + i64 in Rust. Convert one side first: i64::from(count) + bytes. The same goes for f64 and integers: write f64::from(count) * 1.5, not count * 1.5.

    Try it yourself

    Exercise: port this to Rust

    Port this program to Rust. Store the readings as u8 values: each one is between 0 and 255. Watch out: their total isn’t.

    Starting code in TypeScript
    average.ts
    const readings = [200, 180, 250, 90];
    let total = 0;
    for (const reading of readings) {
      total += reading;
    }
    const average = total / readings.length;
    console.log(`total ${total}, average ${average}`);
    Starting code in C#
    Average.cs
    byte[] readings = [200, 180, 250, 90];
    var total = 0; // byte + int is an int in C#
    foreach (var reading in readings)
    {
        total += reading;
    }
    var average = (double)total / readings.Length;
    Console.WriteLine($"total {total}, average {average}");

    Expected output

    total 720, average 180
    Show a hint

    Store the readings as an array of u8. Their total is 720, which doesn't fit in a u8, so add them into a wider type: u32::from(reading). Then convert the total and the length to f64 before dividing.

    Show a solution
    fn main() {
        let readings: [u8; 4] = [200, 180, 250, 90];
        let mut total: u32 = 0;
        for reading in readings {
            total += u32::from(reading);
        }
        let average = f64::from(total) / readings.len() as f64;
        println!("total {total}, average {average}");
    }

    Each reading fits in a u8, but the sum doesn't, so total is a u32 and every reading is widened with u32::from. Dividing needs two f64 values: f64::from(total) is lossless, and readings.len() as f64 is the usual way to turn a usize into a float.