Vectors and Strings

Programming Languages · Rust Data · 12 min

Keep lists of values in a Vec, and build and explore text with String.

A list with Vec

A Vec (vector) is a list that can grow. Make one with vec!. To add to it, it must be mut:

let mut nums = vec![1, 2, 3];
nums.push(4);       // add to the end
println!("{}", nums.len()); // 4

.len() tells you how many items it holds.

  • Add "cherry" to fruits with push.

  • Print 3 fruits using fruits.len().

Getting items by position

Get an item by its position (its index) in square brackets. Counting starts at 0, so the first item is [0]:

let colors = vec!["red", "green"];
println!("{}", colors[0]); // red

Asking for a position that doesn't exist stops the program with an error (Rust calls it a panic).

  • Print First: 70 using scores[0].

  • Print Last: 92 using an index into scores.

Looping over a Vec

Use for to visit every item. Put & in front of the vector to borrow it, just like in the ownership lesson. Without &, the loop takes the vector and you can't use it afterwards:

for color in &colors {
    println!("{}", color);
}
println!("{}", colors.len()); // still works
  • Loop over &names and print Hello, plus each name plus !.

  • After the loop, print 3 people using names.len().

Growing a String, and format!

A String can grow, if it's mut. push_str adds text to the end.

format! works just like println!, but instead of printing, it gives you back a new String:

let mut s = String::from("Hi");
s.push_str(" there");
let line = format!("{}, friend", s); // "Hi there, friend"
  • Add " morning" to greeting with push_str, then print greeting.

  • Use format! to make line, which is greeting followed by , Ada!. Then print line.

Letter by letter with chars()

.chars() lets you walk through a string one character at a time:

for c in "hey".chars() {
    println!("{}", c);
}

And .chars().count() tells you how many characters there are.

  • Loop over word.chars() and print each letter on its own line.

  • After the loop, print 4 letters using word.chars().count().

Put it together: a shopping list

Vec::new() makes an empty vector. The Vec<&str> part says what goes in it: pieces of text. Fill the list, print it, and finish with a summary line built with format!.

  • Push "milk", "bread" and "eggs" into items.

  • Loop over &items and print each one as - milk, - bread, - eggs.

  • Make summary with format! and items.len(), so it says 3 items, and print it.

More in Rust Data

Previous: Enums and match · Next: HashMaps and Errors