Common Collections Flashcards
What do vectors allow for?
Storing more than one value in a single data structure that puts all the values next to each other in memory.
What is the syntax to create a new empty vector?
let v: Vec = Vec::new();
What does let v = vec![1, 2, 3]; do
Uses the vec macro to create a new Vec that holds the values 1, 2, and 3, and assign it to the variable v.
What is the method used to add values to a vector?
push()
What are the two ways to read values from a vector?
By using & and [], which gives a reference, or by using the get method with the index passed as an argument, which gives an Option.
How can you iterate over a vector v?
for i in &mut v { // Do something. }
How can we store multiple types in a vector?
Create an enum with whatever types needed, and a vector that stores the enum type.
How are strings implemented in Rust?
As a collection of bytes, plus some methods to provide useful functionality when those bytes are interpreted as text.
What is the one string type in the Rust core language?
The string slice str that is usually seen in its borrowed form &str
Where is Rusts String type provided?
The standard library.
What is the encoding for both String and string slices?
UTF-8
What is the syntax to create a new String in Rust?
let mut s = String::new();
What does the to_string() do on a string literal?
Creates a String from a string literal. let s = "initial contents".to_string();
What does the String::from function do?
Creates a String for a string literal. let s = String::from("initial contents");
What is the method to push to a string slice?
push_str().
What does the push method do to a String?
Takes a single character as a param and adds it to the string.
What are two ways to concatenate strings in Rust?
+ and format!
What is a String in Rust?
A wrapper over a Vec.
Why is referencing into a String by index not allowed in Rust?
Because it would return the byte value corresponding to the index which might not equate to a correct unicode scalar value. Also because indexing operations are supposed to take O(1) and Rust cannot guarantee that.
What does the chars() do when used with a string?
Iterates over the string returning each Unicode scalar value.
What does the bytes() do when used with a string
Iterates over the string and returns each byte.
What is the use statement for HashMap?
use std::collections::HashMap;
What is the syntax to create a new HashMap?
let mut scores = HashMap::new();