Common rust collections

Storing lists of values with vectors

Vectors allow you to store more than one value in a single data structure that puts all values next to each other in memory.

// create new empty vector
let v: Vec<i32> = Vec::new();
// updating a vector with `push`
v.push(5);
v.push(123);
// creating a new vector containing values
// type is infered
let v = vec![1, 2, 3];
 
// read elements with indexing syntax
// vectors are indexed starting at zero
let third: &i32 = &v[2];
println!("The third element is {}", third);
 
// read element with `get`
match v.get(2) {
    Some(third) => println!("The third element is {}", third),
    None => println!("There is no third element."),
}
 
// iterating over the element using a `for` loop
let v = vec![100, 32, 57];
for i in &v {
    println!("{}", i);
}
 
// iterating over mutable references to elements in a vector
let mut v = vec![100, 32, 57];
for i in &mut v {
    *i += 50;
}

Storing UTF-8 encoded text with Strings

// create new empty string
let mut s = String::new();
 
// using to_string method to create a String from a string literal
let data = "initial contents";
let s = data.to_string();
let s = "initial contents".to_string();
 
// using String::from
let mut s = String::from("initial contents");
// appending a string slice to a String
s.push_str("foobar");
 
// concatenation with the + operator
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
 
// concatenation with the format! macro
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{}-{}-{}", s1, s2, s3);

Rust strings don’t support indexing, i.e. it’s not possible to do the following:

fn main() {
    let s1 = String::from("hello");
    let h = s1[0];
}

A String is a wrapper over a Vec<u8> which is the numerical representation of the characters.

To iterate over strings:

for c in "नमस्ते".chars() {
    println!("{}", c);
}
 
// `bytes` method returns each raw byte
for b in "नमस्ते".bytes() {
    println!("{}", b);
}

Storing keys with associated values in hash maps

// creating new hash map and insert some keys and values
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
 
// creating a hash map from a list of teams and a list of scores
use std::collections::HashMap;
 
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
 
let mut scores: HashMap<_, _> =
    teams.into_iter().zip(initial_scores.into_iter()).collect();

Hash maps and ownership

use std::collections::HashMap;
 
let field_name = String::from("Favorite color");
let field_value = String::from("Blue");
 
let mut map = HashMap::new();
map.insert(field_name, field_value);
// field_name and field_value are invalid at this point, try using them and
// see what compiler error you get!

Accessing values in a hash map

use std::collections::HashMap;
 
let mut scores = HashMap::new();
 
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
 
let team_name = String::from("Blue");
let score = scores.get(&team_name);
 
// iterate over each key/value pair
for (key, value) in &scores {
    println!("{}: {}", key, value);
}

Updating a Hash map

use std::collections::HashMap;
 
let mut scores = HashMap::new();
 
scores.insert(String::from("Blue"), 10);
// override a value
scores.insert(String::from("Blue"), 25);
 
println!("{:?}", scores);
use std::collections::HashMap;
 
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
// entry method to only insert if the key does not already have a value
scores.entry(String::from("Yellow")).or_insert(50);
scores.entry(String::from("Blue")).or_insert(50);
 
println!("{:?}", scores);
use std::collections::HashMap;
 
let text = "hello world wonderful world";
 
let mut map = HashMap::new();
 
// updating a value based on the old value
for word in text.split_whitespace() {
    let count = map.entry(word).or_insert(0);
    *count += 1;
}
 
println!("{:?}", map);