Vector, String, Hash map

Vectors

Vec<T>, vectors store contiguous values in memory.

  let v: Vec<i32> = Vec::new();
  let v: Vec<i32> = vec![1, 2 ,3];

Updating

  v.push(5);

Reading

let third: &i32 = &v[2]; // can cause panic
let third: Option<&i32> = v.get(2); // None means failure
Iterating Values

For each iterator gets immutable references to each element in vector

for item in &v {
  println!("{item}")
}
for item in &mut v {
  *i += 50; // add 50 to all items
}
Using Enum to Store Multiple Types
    enum SpreadsheetCell {
        Int(i32),
        Float(f64),
        Text(String),
    }
    let row = vec![
        SpreadsheetCell::Int(3),
        SpreadsheetCell::Text(String::from("blue")),
        SpreadsheetCell::Float(10.12), ];

Strings

Strings are in the context of collections as they are a collection of bytes.

  • Indexing of Strings is complicated by differences between how humans and computers interpret String data
  • Strings store UTF-8 encoded data.
  • String literals are stored within the program’s binary
Creating a New String
  • Many operations available to Vec<T> are available to String as well.
  • String is very similar to Vec since it is just a wrapper to Vec with some extra guarantees.
let mut s = String::new();
let data = "initial contents";
let s = data.to_string();
let s = String::from("initial contents"); // same as to_string
Combining Strings
let s = format!("{s1}-{s2}-{s3}");

Use format! macro instead adding strings together like:

    let s = s1 + "-" + &s2 + "-" + &s3;
Interpreting Strings

Since strings are in UTF-8, they have variable bytes and it is not easy to index a particular character of a string. Same with slicing, a string slice would mean slicing between bytes, not characters themselves.

Iterating Through Strings
for c in "Зд".chars() { 
  println!("{c}"); 
}
  • str.chars()
  • str.bytes()

Hashmaps

HashMap<K, V>

Creating a New HashMap
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
Updating Hashmap
  • Inserting same key will update key
  • Can update key only if not present like so:
scores.entry(String::from("Yellow")).or_insert(50);
  • Can update key based on old value like so:
let count = map.entry(word).or_insert(0);
*count += 1;