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.

Memory LayoutRust Standard Collectionspoints toVec<T>Dynamically sized ordered listStringUTF-8 encoded bytes wrapperHashMap<K, V>Key-Value lookup tableStack: Pointer + Capacity +LengthHeap: Dynamic buffer allocation

Vectors (Vec<T>)#

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

Heap MemoryStack Memoryvecptrcap: 4len: 3[0]: 10[1]: 20[2]: 30[3]: Unallocated

UTF-8 Strings (String)#

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

Heap BufferStack Frames (String)ptrcap: 7len: 7'f' (102)'o' (111)'o' (111)'b' (98)'a' (97)'r' (114)'!' (33)
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:

Bucket Array on HeapHash FunctionKey: 'Blue'Hash('Blue')Key: 'Yellow'Hash('Yellow')Bucket 2: ('Blue', 10)Bucket 5: ('Yellow', 50)

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#