DEV Community

BC
BC

Posted on • Edited on

Day8:Common Collections - 100DayOfRust

Common Collections

Heard some people complained that after learning the basics of Rust, they still don't know how to implement a linked list in Rust because of the complicated ownership system. While you can implement it with the Box<> pointer, the good news is, Rust has built-in collections you can use, just like C++'s STL, so you don't have to implement those by yourself.

Below are examples of usage of Vector, VecDeque, LinkedList, HashMap, BTreeMap and HashSet:

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

fn main() {
    // Vector
    let mut v = Vec::new();
    v.push(1);
    v.push(2);
    println!("Vector: {:?}", v);
    v.pop();
    println!("Vector: {:?}", v);

    // Deque
    let mut vd = VecDeque::new();
    vd.push_back(1);
    vd.push_back(2);
    vd.push_back(3);
    println!("Deque: {:?}", vd);
    vd.pop_front();
    println!("Deque: {:?}", vd);

    // Linked List
    let mut list = LinkedList::new();
    list.push_back(1);
    list.push_back(2);
    list.push_back(3);
    println!("List: {:?}", list);
    list.pop_front();
    println!("List: {:?}", list);

    // HashMap
    let mut hm = HashMap::new();
    hm.insert("Alice", 90);
    hm.insert("Bob", 85);
    println!("HashMap: {:?}", hm);
    println!("Alice: {}", hm.get("Alice").unwrap());
    hm.remove("Alice");
    println!("Alice: {:?}", hm.get("Alice"));

    // BTreeMap
    let mut bm = BTreeMap::new();
    bm.insert("Alice", 90);
    bm.insert("Bob", 85);
    println!("BTreeMap: {:?}", bm);
    println!("Alice: {}", bm.get("Alice").unwrap());
    bm.remove("Alice");
    println!("Alice: {:?}", bm.get("Alice"));

    // HashSet
    let mut hs = HashSet::new();
    hs.insert("Alice");
    hs.insert("Bob");
    hs.insert("Alice");
    println!("HashSet: {:?}", hs);
    hs.remove("Alice");
    println!("HashSet: {:?}", hs);
}
Enter fullscreen mode Exit fullscreen mode

Result:

Vector: [1, 2]
Vector: [1]
Deque: [1, 2, 3]
Deque: [2, 3]
List: [1, 2, 3]
List: [2, 3]
HashMap: {"Bob": 85, "Alice": 90}
Alice: 90
Alice: None
BTreeMap: {"Alice": 90, "Bob": 85}
Alice: 90
Alice: None
HashSet: {"Bob", "Alice"}
HashSet: {"Bob"}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
anujborah1 profile image
anujborah1

// BTreeMap
let mut bm = BTreeMap::new();
bm.insert("Alice", 90);
bm.insert("Bob", 85);
println!("BTreeMap: {:?}", bm);
println!("Alice: {}", bm.get("Alice").unwrap());
hm.remove("Alice"); ---- may be this one should be bm.remove();
println!("Alice: {:?}", bm.get("Alice"));

Collapse
 
bitecode profile image
BC

oh, you are right, I just fixed it, thank you for pointing out :D