Algorithms and Data Structures in Rust: A Beginner's Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Algorithms and Data Structures in Rust: A Complete Guide for Beginners



Rust is a programming language that combines the high performance of C/C++ with memory safety guaranteed at compile time. For beginner developers, learning algorithms and data structures in Rust is not only a way to master fundamental Computer Science concepts but also an opportunity to understand the language's unique features: ownership, borrowing, and lifetimes.



In this article, we will cover the key data structures and algorithms that every developer should know. All code examples are written in Rust and ready to run. We will start with the basic structures provided by the standard library and then move on to implementing classic algorithms.



1. Basic Data Structures in Rust



The Rust standard library (std) provides a rich set of ready-made data structures. Let's look at the three most important ones.



Vectors (Vec)

Vec is a dynamic array that can change its size. It is analogous to ArrayList in Java or list in Python. Vectors guarantee contiguous memory layout, making index access very fast (O(1)).



fn main() {    // Creating an empty vector    let mut numbers: Vec<i32> = Vec::new();        // Adding elements    numbers.push(10);    numbers.push(20);    numbers.push(30);        // Index access    let first = numbers[0]; // 10        // Iteration    for num in &numbers {        println!("{}", num);    }        // vec! macro    let fruits = vec!["apple", "banana", "cherry"];    println!("Second fruit: {}", fruits[1]); // banana}


Hash Maps (HashMap)

HashMap is a data structure that stores key-value pairs. It provides average O(1) time for insertion, lookup, and deletion. It is ideal for tasks where you need to quickly find data by key.



use std::collections::HashMap;

fn main() { let mut scores = HashMap::new(); scores.insert(String::from("Alice"), 100); scores.insert(String::from("Bob"), 85); // Getting a value by key let alice_score = scores.get(&String::from("Alice")); match alice_score { Some(score) => println!("Alice scored: {}", score), None => println!("Alice not found"), } // Iterating over all pairs for (name, score) in &scores { println!("{}: {}", name, score); }}


Strings (String)

In Rust, there are two main string types: &str (string slice) and String (mutable, owning string). Working with strings in Rust requires attention due to UTF-8 encoding.



fn main() {    let mut hello = String::from("Hello, ");    hello.push_str("world!"); // Appending a string    hello.push('!'); // Appending a character        println!("{}", hello); // Hello, world!!        // String slices (be careful with character boundaries!)    let slice = &hello[0..5]; // "Hello"    println!("Slice: {}", slice);}


2. Implementing Stack and Queue



Stack and queue are fundamental data structures often used in algorithms. In Rust, they can be easily implemented using Vec.



Stack (LIFO — Last In, First Out)

A stack operates on the principle of "last in, first out." Vec already provides push and pop methods that implement stack behavior.



fn main() {    let mut stack: Vec<i32> = Vec::new();        stack.push(1);    stack.push(2);    stack.push(3);        while let Some(top) = stack.pop() {        println!("Popping: {}", top);    }    // Output: 3, 2, 1}


Queue (FIFO — First In, First Out

Blogs

Book Recommendations