FerrousPath

Level 1 · Foundations· Lesson 8 of 10 · 25 min

Collections and strings

Vec, String and HashMap — the three collections you will use daily — and why you cannot index a string.

Vec<T>: a growable array

fn main() {
    let mut v: Vec<i32> = Vec::new();
    v.push(10);
    v.push(20);
    v.push(30);

    let w = vec![1, 2, 3]; // the vec! macro builds one from a list

    println!("{v:?} {w:?} len={} first={}", v.len(), v[0]);

    // Two ways to read an element:
    let third = v[2];           // panics if out of bounds
    let maybe = v.get(99);      // returns Option<&i32>
    println!("{third} {maybe:?}");

    // Iterating: by shared reference, by mutable reference, by value.
    for x in &v {
        print!("{x} ");
    }
    for x in &mut v {
        *x *= 2; // dereference to modify the element
    }
    println!("\n{v:?}");
    for x in v {
        print!("{x} "); // consumes v
    }
    // v is gone now.
}

A Vec owns its elements: dropping the vector drops everything in it. Useful methods: pop, insert, remove, contains, sort, dedup, retain, extend, iter, first, last, is_empty.

Strings

Rust has two main string types:

Type Owned? Growable? Where the bytes live
String yes yes heap
&str no — it is a borrowed slice no anywhere: a String, the program binary, …

String literals like "hello" are &'static str, baked into the binary. Both types are always valid UTF-8.

fn main() {
    let mut s = String::new();
    s.push_str("hello");
    s.push(' ');
    s += "world";

    let name = "Ferris";
    let greeting = format!("{s}, {name}!"); // format! builds a String
    println!("{greeting}");

    let owned: String = "literal".to_string();
    let borrowed: &str = &owned;
    println!("{owned} {borrowed}");
}

Why s[0] does not exist

fn main() {
    let word = "naïve 🦀";
    println!("bytes: {}", word.len());            // 11, not 7
    println!("chars: {}", word.chars().count());  // 7

    for c in word.chars() {
        print!("[{c}]");
    }
    println!();
    println!("{:?}", word.bytes().take(4).collect::<Vec<u8>>());

    println!("{}", &word[0..2]);  // byte range: fine, "na"
    // println!("{}", &word[0..3]); // would panic: byte 3 is inside 'ï'
    println!("{:?}", word.char_indices().nth(2));
}

In UTF-8, ï takes two bytes and 🦀 takes four. Integer indexing would have to choose between returning a byte (often meaningless) and scanning from the start (slow, and hidden). Rust offers neither; you choose .bytes(), .chars(), or a byte-range slice explicitly.

Handy string methods: trim, split, split_whitespace, lines, contains, starts_with, replace, to_uppercase, parse, find.

HashMap<K, V>

use std::collections::HashMap;

fn main() {
    let mut stock: HashMap<String, u32> = HashMap::new();
    stock.insert(String::from("apples"), 3);
    stock.insert(String::from("pears"), 5);

    if let Some(n) = stock.get("apples") {
        println!("{n} apples");
    }
    println!("kiwis: {}", stock.get("kiwis").copied().unwrap_or(0));

    // The entry API: update-or-insert in one lookup.
    let text = "the quick brown fox jumps over the lazy dog the end";
    let mut counts: HashMap<&str, u32> = HashMap::new();
    for word in text.split_whitespace() {
        *counts.entry(word).or_insert(0) += 1;
    }

    let mut pairs: Vec<_> = counts.into_iter().collect();
    pairs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
    for (word, n) in pairs.iter().take(3) {
        println!("{word}: {n}");
    }
}

Iteration order of a HashMap is arbitrary and differs between runs. Use BTreeMap when you need keys in sorted order. Inserting an owned key such as a String moves it into the map.

Other collections in std::collections: HashSet, BTreeMap, BTreeSet, VecDeque (a double-ended queue), and BinaryHeap (a priority queue).

Exercises

  1. Given a Vec<i32>, compute the mean, the median (sort first), and the mode (use a HashMap).
  2. Write fn is_palindrome(s: &str) -> bool that ignores case and non-alphanumeric characters.
  3. Write fn pig_latin(word: &str) -> String: words starting with a vowel get -hay appended; otherwise the first letter moves to the end followed by ay (first → irst-fay).
Solution to 2
fn is_palindrome(s: &str) -> bool {
    let cleaned: Vec<char> = s
        .chars()
        .filter(|c| c.is_alphanumeric())
        .flat_map(|c| c.to_lowercase())
        .collect();
    cleaned.iter().eq(cleaned.iter().rev())
}

fn main() {
    println!("{}", is_palindrome("A man, a plan, a canal: Panama"));
    println!("{}", is_palindrome("Rust"));
}

Check your understanding

Pick an answer to see the explanation.

  1. 1.Why does let s = String::from("héllo"); let c = s[1]; not compile?

  2. 2.What does v.get(10) return on a 3-element vector?

  3. 3.What does *map.entry(k).or_insert(0) += 1 do?

Key terms in this lesson

Finished the lesson and the exercises?