Detailed Explanation and Examples of Common Types in the Rust Standard Library

This article will help you systematically master the most commonly used core types in the Rust standard library.

Including: Box, Rc, Vec, HashMap, various string types, and time management.

🌈 Coverage

  • Smart Pointer: Box
  • Reference Counting: Rc
  • Dynamic Array: Vec
  • Key-Value Storage: HashMap
  • String Family: String, &str, OsString, CString, etc.
  • Time and Timing: SystemTime, Instant, Duration

🧱 1. Box— Heap-Allocated Smart Pointer

Concept

  • <span>Box<T></span> places a value on the heap, with a pointer stored on the stack.
  • Suitable for large runtime sizes or recursive data structures.

Common Scenarios

  • Heap-allocating large objects to reduce stack space pressure.
  • Recursive structures like linked lists and trees.

Main API

  • <span>Box::new(value)</span>
  • Dereference <span>*bx</span>
  • Automatically releases resources, adhering to ownership transfer.

Example: Basic Usage

fn main() {    let x = 42;    let bx = Box::new(x);    println!("bx = {}, *bx = {}", bx, *bx);    let by = bx;    println!("by = {}", by);}

Example: Recursive Structure

enum List {    Cons(i32, Box<List>),    Nil,}use List::{Cons, Nil};impl List {    fn len(&self) -> usize {        match self {            Cons(_, tail) => 1 + tail.len(),            Nil => 0,        }    }}fn main() {    let l = Cons(1, Box::new(Cons(2, Box::new(Nil))));    println!("len = {}", l.len());}

📎 Note: Box does not share ownership; use <span>Rc</span> or <span>Arc</span> for shared ownership.

🔁 2. Rc— Single-threaded Shared Reference Counting

Concept

  • <span>Rc<T></span> provides read access with multiple owners.
  • Recovers memory when the last owner is released through reference counting.

Usage

  • Accessing the same object from multiple places, requiring only read access.
  • Sharing nodes in single-threaded graphs or tree structures.

Example

use std::rc::{Rc, Weak};fn main() {    let a = Rc::new(String::from("shared"));    let b = Rc::clone(&a);    println!("count = {}", Rc::strong_count(&a));    let w: Weak<String> = Rc::downgrade(&a);    println!("upgrade = {:?}", w.upgrade());    drop(b);    println!("after drop: {}", Rc::strong_count(&a));    drop(a);    println!("upgrade after drop all -> {:?}

Leave a Comment