Rust Standard Library

Essential modules and functions built into Rust

๐Ÿ“š What is Rust Standard Library?

Rust's standard library provides essential functionality like collections, I/O operations, string handling, and system interfaces. It's automatically available in every Rust program, offering powerful tools for common programming tasks.


// Using standard library modules
use std::collections::HashMap;
use std::fs;

fn main() {
    let mut map = HashMap::new();
    map.insert("key", "value");
    println!("{:?}", map);
}
                                    

Output:

{"key": "value"}

Standard Library Modules

๐Ÿ“ฆ

Collections

Data structures for storing data

use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("key", "value");
๐Ÿ“

File System

Reading and writing files

use std::fs;
let content = fs::read_to_string("file.txt")?;
๐ŸŒ

Networking

Network communication

use std::net::TcpStream;
let stream = TcpStream::connect("127.0.0.1:8080")?;
๐Ÿงต

Threading

Concurrent programming

use std::thread;
thread::spawn(|| {
    println!("Hello from thread!");
});

๐Ÿ”น Collections Module

The collections module provides efficient data structures:

use std::collections::{HashMap, HashSet, VecDeque, BTreeMap};

fn collections_demo() {
    // HashMap - key-value pairs
    let mut scores = HashMap::new();
    scores.insert("Alice", 95);
    scores.insert("Bob", 87);
    println!("Alice's score: {:?}", scores.get("Alice"));
    
    // HashSet - unique values
    let mut unique_numbers = HashSet::new();
    unique_numbers.insert(1);
    unique_numbers.insert(2);
    unique_numbers.insert(1); // Duplicate ignored
    println!("Unique numbers: {:?}", unique_numbers);
    
    // VecDeque - double-ended queue
    let mut deque = VecDeque::new();
    deque.push_back(1);
    deque.push_front(0);
    println!("Deque: {:?}", deque);
    
    // BTreeMap - sorted key-value pairs
    let mut sorted_map = BTreeMap::new();
    sorted_map.insert("zebra", 1);
    sorted_map.insert("apple", 2);
    for (key, value) in &sorted_map {
        println!("{}: {}", key, value); // Prints in alphabetical order
    }
}

Output:

Alice's score: Some(95)
Unique numbers: {1, 2}
Deque: [0, 1]
apple: 2
zebra: 1

๐Ÿ”น File System Operations

Working with files and directories using std::fs:

use std::fs;
use std::io::prelude::*;
use std::path::Path;

fn file_operations() -> std::io::Result<()> {
    // Write to a file
    fs::write("example.txt", "Hello, Rust!")?;
    
    // Read entire file as string
    let content = fs::read_to_string("example.txt")?;
    println!("File content: {}", content);
    
    // Read file as bytes
    let bytes = fs::read("example.txt")?;
    println!("File size: {} bytes", bytes.len());
    
    // Check if file exists
    if Path::new("example.txt").exists() {
        println!("File exists!");
    }
    
    // Get file metadata
    let metadata = fs::metadata("example.txt")?;
    println!("File size: {} bytes", metadata.len());
    println!("Is file: {}", metadata.is_file());
    
    // Create directory
    fs::create_dir_all("my_folder/subfolder")?;
    
    // List directory contents
    for entry in fs::read_dir(".")? {
        let entry = entry?;
        println!("Found: {:?}", entry.file_name());
    }
    
    // Remove file
    fs::remove_file("example.txt")?;
    
    Ok(())
}

Common File Operations:

โ€ข fs::write() - Write data to file
โ€ข fs::read_to_string() - Read file as string
โ€ข fs::create_dir_all() - Create directories
โ€ข Path::exists() - Check if path exists

๐Ÿ”น String Processing

String manipulation with the standard library:

fn string_operations() {
    let text = "  Hello, Rust World!  ";
    
    // String methods
    println!("Original: '{}'", text);
    println!("Trimmed: '{}'", text.trim());
    println!("Uppercase: '{}'", text.to_uppercase());
    println!("Lowercase: '{}'", text.to_lowercase());
    
    // String searching
    println!("Contains 'Rust': {}", text.contains("Rust"));
    println!("Starts with 'Hello': {}", text.trim().starts_with("Hello"));
    println!("Ends with '!': {}", text.trim().ends_with("!"));
    
    // String splitting
    let words: Vec<&str> = text.trim().split_whitespace().collect();
    println!("Words: {:?}", words);
    
    let parts: Vec<&str> = text.trim().split(',').collect();
    println!("Parts: {:?}", parts);
    
    // String replacement
    let replaced = text.replace("Rust", "Programming");
    println!("Replaced: '{}'", replaced.trim());
    
    // String formatting
    let name = "Alice";
    let age = 30;
    let formatted = format!("Name: {}, Age: {}", name, age);
    println!("{}", formatted);
    
    // String building
    let mut builder = String::new();
    builder.push_str("Hello");
    builder.push(' ');
    builder.push_str("World");
    println!("Built string: {}", builder);
}

Output:

Original: ' Hello, Rust World! '
Trimmed: 'Hello, Rust World!'
Uppercase: ' HELLO, RUST WORLD! '
Contains 'Rust': true
Words: ["Hello,", "Rust", "World!"]
Name: Alice, Age: 30

๐Ÿ”น Threading and Concurrency

Basic threading with std::thread:

use std::thread;
use std::time::Duration;
use std::sync::{Arc, Mutex};

fn threading_examples() {
    // Basic thread creation
    let handle = thread::spawn(|| {
        for i in 1..=5 {
            println!("Thread: {}", i);
            thread::sleep(Duration::from_millis(100));
        }
    });
    
    // Main thread work
    for i in 1..=3 {
        println!("Main: {}", i);
        thread::sleep(Duration::from_millis(150));
    }
    
    // Wait for thread to finish
    handle.join().unwrap();
    
    // Shared data with Arc and Mutex
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    
    for _ in 0..3 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
            println!("Thread incremented counter to: {}", *num);
        });
        handles.push(handle);
    }
    
    // Wait for all threads
    for handle in handles {
        handle.join().unwrap();
    }
    
    println!("Final counter value: {}", *counter.lock().unwrap());
}

Threading Concepts:

โ€ข thread::spawn() - Create new thread
โ€ข handle.join() - Wait for thread completion
โ€ข Arc<Mutex<T>> - Shared mutable data
โ€ข thread::sleep() - Pause execution

๐Ÿ”น Time and Duration

Working with time using std::time:

use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use std::thread;

fn time_examples() {
    // Measuring elapsed time
    let start = Instant::now();
    
    // Simulate some work
    thread::sleep(Duration::from_millis(100));
    
    let elapsed = start.elapsed();
    println!("Operation took: {:?}", elapsed);
    
    // Creating durations
    let one_second = Duration::from_secs(1);
    let half_second = Duration::from_millis(500);
    let microseconds = Duration::from_micros(1000);
    
    println!("1 second = {} milliseconds", one_second.as_millis());
    println!("500ms = {} microseconds", half_second.as_micros());
    
    // System time (wall clock time)
    let now = SystemTime::now();
    let since_epoch = now.duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    
    println!("Seconds since Unix epoch: {}", since_epoch.as_secs());
    
    // Time arithmetic
    let future = now + Duration::from_secs(60);
    println!("One minute from now: {:?}", future);
}

Time Operations:

โ€ข Instant::now() - High-precision timing
โ€ข SystemTime::now() - Wall clock time
โ€ข Duration - Time spans
โ€ข elapsed() - Measure time differences

๐Ÿง  Test Your Knowledge

Which standard library module provides HashMap?