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"tofruitswithpush.Print
3 fruitsusingfruits.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: 70usingscores[0].Print
Last: 92using an index intoscores.
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
&namesand printHello,plus each name plus!.After the loop, print
3 peopleusingnames.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"togreetingwithpush_str, then printgreeting.Use
format!to makeline, which isgreetingfollowed by, Ada!. Then printline.
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 lettersusingword.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"intoitems.Loop over
&itemsand print each one as- milk,- bread,- eggs.Make
summarywithformat!anditems.len(), so it says3 items, and print it.
More in Rust Data
Previous: Enums and match · Next: HashMaps and Errors