← Zurück zum Kurs: Rust from scratch

Vec and String in depth

Video folgt in Kürze

Arrays have a fixed size, but you almost always need collections that grow while the program runs. The standard library offers collections that store their data on the heap. The two most used are Vec<T>, a growable list of elements of the same type, and String, a growable UTF-8 text. In this lesson you will learn to create, modify and walk them, and why text in Rust has rules that surprise people coming from other languages.

Vec<T>

You create an empty vector with Vec::new() or, with initial values, with the vec![] macro. You add with push, remove the last one with pop (it returns an Option) and ask the size with len. There are two ways to read an element: v[2] panics if the index does not exist, while v.get(2) returns an Option and lets you decide. To walk it you use for over &v (read only), &mut v (modify each element) or v (consume the vector). Remember the borrowing rules: while you hold a reference to an element, you cannot push, because the vector could be relocated in memory.

rust
fn main() {
    let mut scores: Vec<i32> = Vec::new();
    scores.push(70);
    scores.push(85);
    scores.push(92);

    let mut names = vec!["Ana", "Luis"];
    names.push("Eva");
    println!("{:?} {}", names, names.len());

    println!("{:?} {:?}", scores.get(1), scores.get(10));

    for s in &mut scores {
        *s += 5; // modify each element through the reference
    }
    println!("{:?}", scores);

    let last = scores.pop();
    println!("{:?} -> {:?}", last, scores);

    scores.sort();
    scores.insert(0, 1);
    scores.retain(|&n| n > 50);
    println!("{:?} contains 80? {}", scores, scores.contains(&80));
}

String and &str

String is an owned text, which grows and lives on the heap; &str is a read-only view over text. You create a String with String::from("hello") or "hello".to_string(). To append you use push (a char) or push_str (a &str); you can also join with the + operator (which moves the first String) or, better, with format!, which takes ownership of nothing. Strings are UTF-8: each character takes 1 to 4 bytes. That is why Rust does not allow s[0]; there is no single answer to "the first letter" without deciding whether you mean bytes, characters (chars) or graphemes.

rust
fn main() {
    let mut s = String::from("rust");
    s.push('!');
    s.push_str(" is fun");
    println!("{s}");

    let a = String::from("Hello, ");
    let b = String::from("world");
    let joined = format!("{a}{b}"); // a and b still usable
    println!("{joined}");
    let moved = a + &b;             // a is moved here
    println!("{moved}");

    let word = "niño";
    println!("bytes = {}, chars = {}", word.len(), word.chars().count());
    for c in word.chars() {
        print!("[{c}]");
    }
    println!();

    let text = "  one, two,three  ";
    let parts: Vec<&str> = text.trim().split(',').map(|p| p.trim()).collect();
    println!("{:?}", parts);
    println!("{}", "abc".repeat(2).to_uppercase().replace("B", "-"));
}

A classic error with Vec

This program does not compile on purpose. We keep a reference to the first element and then add another one: push might force the vector to move to another place in memory, leaving the reference pointing to garbage. In C++ that is a silent bug; in Rust it is a compile error. Fix the code by pushing before taking the reference, or by copying the value (let first = v[0]; works with i32 because it is Copy).

rust
// Does NOT compile on purpose: reference alive while the Vec may reallocate
fn main() {
    let mut v = vec![1, 2, 3];
    let first = &v[0];
    v.push(4); // error: cannot borrow `v` as mutable
    println!("{first}");
}
rust
fn main() {
    let mut words: Vec<String> = vec!["pear", "apple", "grape", "kiwi"]
        .into_iter()
        .map(String::from)
        .collect();
    words.sort();

    let mut line = String::new();
    let mut long_words = 0;
    for w in &words {
        if !line.is_empty() {
            line.push_str(" - ");
        }
        line.push_str(w);
        if w.chars().count() > 4 {
            long_words += 1;
        }
    }
    println!("{line}");
    println!("{long_words} long words");
}

Teste dein Wissen

Frage 1 von 4

What does v.get(10) return if the vector has 3 elements?

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →