Chapter 18: Common Collection Types

In C programming, managing groups of data elements whose size is unknown at compile time typically requires manual memory management using functions like malloc, realloc, and free. While flexible, this approach is notoriously prone to errors, including memory leaks, double frees, use-after-free bugs, and buffer overflows, which can lead to crashes or security vulnerabilities.

Rust provides built-in collection types to handle dynamic data safely and efficiently. These are data structures capable of storing multiple values. Unlike fixed-size arrays or tuples, standard collections such as Vec<T>, String, and HashMap<K, V> store their data on the heap and can grow or shrink as needed during program execution. They abstract away the complexities of manual memory management, leveraging Rust’s ownership and borrowing system to guarantee memory safety without sacrificing performance.

This chapter introduces the most frequently used collection types in Rust. We will explore their characteristics, compare them with C idioms and fixed-size Rust types, and demonstrate how they facilitate dynamic data management safely.