Monday, May 22, 2023

Rust Collections

 




This post contains short cheat-sheets examples for the collections: vectors, strings, and hashmap.


Vectors


// vector without initial value must have the type specified
let v1: Vec<i32> = Vec::new();
// type of vector with initialization is automatically derived
let mut v1 = vec![1, 2, 3];

// add values
v1.push(72);

// direct access to element
let second_item = v1[1];
println!("second item is {second_item}");

// direct access will get error if index of of bounds
// let non_existing = v1[9999];


// using get, returns an option
let non_existing = v1.get(9999);
match non_existing {
Some(x) => println!("it's there {x}"),
None => println!("you went too far"),
}

let cell_pointer = &v1[0];
v1.push(73);
/*
immutable borrow error here
after adding an element to the vector, we might had to reallocated space and move the array data
hence the cell pointer is no longer valid
*/
// println!("item {cell_pointer}");


// update loop on vector
for item in &mut v1 {
*item += 100;
}

// read only loop on vector
for item in &v1 {
println!("vector item {item}");
}


Strings

// new empty String
let mut s1 = String::new();


// String from str alternatives
let data = "One method";
let s2 = data.to_string();
let s3 = String::from("Another method");

// updating a string
let mut updated_string = String::from("start");
updated_string.push_str(" and end");
updated_string.push('!');
println!("updated string to {updated_string}");

// concatenation
let con1 = String::from("Foo");
let con2 = String::from("Bar");
let con3 = String::from("!");
let con4 = format!("{con1} {con2} {con3}");
println!("concatenation is {con4}");
let con5 = con1 + " " + &con2 + " " + &con3;
// borrow of moved value error in con5 creation
// println!("concatenation origin {con1}");

// due to unicode issues, we don't access string chars like this s[2]
for c in "יו".chars() {
println!("char {c}");
}
// notice this will be more than 2 bytes, due to unicode
for b in "יו".bytes() {
println!("byte {b}");
}


Hash Maps

use std::collections::HashMap;
let mut workers = HashMap::new();
workers.insert("Alice", 45);
workers.insert("Bob", 34);

// get with default
let alice_age = workers.get("Alice").copied().unwrap_or(0);
let no_one_age = workers.get("No one").copied().unwrap_or(0);
println!("alice is {alice_age} years old, and no one is {no_one_age}");

// loop
for (name, age) in &workers {
println!("worker {name} is {age} years old");
}

// update values
workers.insert("Alice", 46);
let alice_age = workers.get("Alice").copied().unwrap_or(0);
println!("alice is {alice_age} years old now");

// update values only if new key
workers.entry("Alice").or_insert(99);
let alice_age = workers.get("Alice").copied().unwrap_or(0);
println!("alice is (still) {alice_age} years old");

/*
count words by hashmap, while updating values.
notice that we get a pointer to the value, and we update it directly
*/
let mut words = HashMap::new();
for word in "my name is indigo montoya you have killed my father prepare to die".split_whitespace() {
let count = words.entry(word).or_insert(0);
*count += 1;
}
println!("{:?}", words);




No comments:

Post a Comment