Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Collections in Rust

What are Collections?

In Rust, collections are data structures that allow you to store multiple values in a single variable. They are essential for managing groups of related data and provide various functionalities, such as adding, removing, and accessing elements. Rust offers several built-in collection types, each designed for specific use cases.

Types of Collections

Rust provides several types of collections, with the most commonly used being:

  • Vectors: A contiguous growable array type.
  • Strings: A collection of characters.
  • HashMaps: A collection of key-value pairs.
  • BTreeMaps: A sorted collection of key-value pairs.
  • LinkedLists: A doubly-linked list.

Vectors

Vectors are one of the most versatile collections in Rust. They can grow and shrink dynamically, allowing for efficient memory usage. You can create a vector using the vec![] macro.

Example:
let mut numbers = vec![1, 2, 3];
Vector: [1, 2, 3]

You can add elements to a vector using the push method:

Example:
numbers.push(4);
Vector after push: [1, 2, 3, 4]

Strings

Strings in Rust are represented as a collection of characters. The String type is a growable, heap-allocated data structure used to store text.

Example:
let mut greeting = String::from("Hello");
String: "Hello"

You can concatenate strings using the push_str method:

Example:
greeting.push_str(", World!");
String after concatenation: "Hello, World!"

HashMaps

HashMaps are collections of key-value pairs, where each key must be unique. They provide fast access to values based on their keys.

Example:
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert("Alice", 10);
HashMap: {"Alice": 10}

Conclusion

Collections in Rust are a powerful feature that allow developers to manage and manipulate groups of data efficiently. By understanding the different types of collections available, you can choose the right one for your specific use case and leverage their capabilities in your Rust programs.