blog.dopana

Back

Ninth post in the basic Rust series. Unlike built-in arrays and tuples whose sizes are fixed at compile time, collections point to data allocated on the heap and can shrink or grow at runtime.

graph TD
    subgraph Collections["Rust Standard Collections"]
        Vec["Vec&lt;T&gt;<br/>Dynamically sized ordered list"]
        String["String<br/>UTF-8 encoded bytes wrapper"]
        HashMap["HashMap&lt;K, V&gt;<br/>Key-Value lookup table"]
    end

    subgraph Memory["Memory Layout"]
        Stack["Stack: Pointer + Capacity + Length"]
        Heap["Heap: Dynamic buffer allocation"]
    end

    Vec --> Stack
    String --> Stack
    HashMap --> Stack
    Stack -->|points to| Heap

Vectors (Vec<T>)#

A vector stores multiple values of the same type sequentially in memory:

graph LR
    subgraph StackMem["Stack Memory"]
        V["vec"]
        V_ptr["ptr"]
        V_cap["cap: 4"]
        V_len["len: 3"]
    end

    subgraph HeapMem["Heap Memory"]
        H0["[0]: 10"]
        H1["[1]: 20"]
        H2["[2]: 30"]
        H3["[3]: Unallocated"]
    end

    V_ptr --> H0
    H0 --- H1 --- H2 --- H3

UTF-8 Strings (String)#

In Rust, String is a wrapper over a Vec<u8> guaranteed to be valid UTF-8 text:

graph LR
    subgraph StackFrame["Stack Frame"]
        S["s (String)"]
        S_ptr["ptr"]
        S_cap["cap: 7"]
        S_len["len: 7"]
    end

    subgraph HeapBuffer["Heap Buffer"]
        B0["'f' (102)"]
        B1["'o' (111)"]
        B2["'o' (111)"]
        B3["'b' (98)"]
        B4["'a' (97)"]
        B5["'r' (114)"]
        B6["'!' (33)"]
    end

    S_ptr --> B0
    B0 --- B1 --- B2 --- B3 --- B4 --- B5 --- B6
let mut s = String::from("foo");
s.push_str("bar");
s.push('!');

// Concatenation with + or format!
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = format!("{s1}{s2}"); // format! does not take ownership
rust

Because UTF-8 characters vary in byte length (1 to 4 bytes), Rust does not support direct indexing like s[0] to prevent returning invalid character bytes. Instead, use string slices &s[0..4] or iterate with .chars().

Hash Maps (HashMap<K, V>)#

A hash map maps keys of type K to values of type V using a hashing function:

graph LR
    subgraph HashFunc["Hash Function"]
        K1["Key: 'Blue'"] --> H1["Hash('Blue')"]
        K2["Key: 'Yellow'"] --> H2["Hash('Yellow')"]
    end

    subgraph BucketArray["Bucket Array on Heap"]
        H1 --> B1["Bucket 2: ('Blue', 10)"]
        H2 --> B2["Bucket 5: ('Yellow', 50)"]
    end

Conclusion#

Vectors store ordered element lists, Strings manage heap-allocated UTF-8 text safely, and HashMaps manage key-value associations. Next in this series: error handling.

References#