Rust Standard Library: A Complete Overview
The Rust Standard Library (std) is the foundation upon which any application in this language is built. It provides a set of reliable, efficient, and safe tools for solving common tasks, from working with collections to low-level memory management. Unlike many other languages, the Rust standard library is designed to minimize dependence on external crates for basic operations while maintaining performance close to C/C++.
Main Modules of the Standard Library
The standard library is organized into logical modules. Let's look at the key ones:
std::collections— data structures:Vec,HashMap,HashSet,BTreeMap,LinkedList, and others.std::io— input/output operations: reading/writing files, working with streams, buffering.std::fs— file system: creating, deleting, copying files and directories.std::thread— multithreading: creating threads, synchronization viaMutex,Arc.std::sync— synchronization primitives: channels (mpsc), barriers, semaphores.std::net— network programming: TCP/UDP sockets, addresses.std::time— working with time: measurements, timers, durations.std::mem— memory management: type sizes, alignment,swap,replace.
Collections: From Vec to HashMap
Collections in Rust are not just containers. They implement a rich API and guarantee memory safety at compile time. The most popular collection is Vec<T> — a dynamic array.
fn main() { let mut numbers: Vec<i32> = vec![1, 2, 3, 4]; numbers.push(5); // Iteration with modification for num in &mut numbers { *num *= 2; } // Filtering let evens: Vec<&i32> = numbers.iter() .filter(|&&x| x % 2 == 0) .collect(); println!("{:?}", evens); // [2, 4, 6, 8, 10]}HashMap — an associative array with hashing. It is important to note that by default a cryptographically secure hash algorithm (SipHash) is used, which prevents HashDoS attacks.
use std::collections::HashMap;
fn main() { let mut scores = HashMap::new(); scores.insert(String::from("Alice"), 100); scores.insert(String::from("Bob"), 85); // Safe value retrieval match scores.get(&String::from("Alice")) { Some(score) => println!("Score: {}", score), None => println!("Not found"), } // Iteration with an iterator for (name, score) in &scores { println!("{}: {}", name, score); }}Working with Input/Output and Files
The std::io module provides both high-level and low-level tools for working with data streams. The Read and Write traits deserve special attention.
use std::fs::File;use std::io::{self, Read, Write};
fn read_file(path: &str) -> io::Result<String> { let mut file = File::open(path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents)}
fn write_file(path: &str, data: &str) -> io::Result<()> { let mut file = File::create(path)?; file.write_all(data.as_bytes())?; Ok(())}
fn main() -> io::Result<()> { write_file("example.txt", "Hello, Rust Also in library
JSON Processing in C# (.NET): Complete Guide with Examples
Internationalization (i18n) in Swift: NSLocalizedString and String Catalog