# Common Collections Collections are data structures, which Rust provides through its standard library. Collections store data on the heap. # Vectors ``` rust let v: Vec = Vec::new(); ``` If we are not initializing it based on a list of values, you have to specify the type like any other type of variable: `let v = vec![1,2,3];` Using the macro `vec!` creates a `Vector` from the list of items you give it, using the initial type as the type for the new vector. ## Updating a Vector ```rust let mut v = Vec::new(); // No type inferred v.push(); // Add item to the back // Type is now inferred ``` ## Dropping Vector = Dropping Vector's Heap When a vector goes out of scope, ## Reading Elements of a Vector `[index]` direct access or `.get(index)` using match expression: ```rust let third_val = &v[2]; let var = v.get(2); if let Some(var2) = var { // Do something, var is an Option with Some(value of v[2]) or None }; ``` When having access or referencing a value, we can't actually modify the vector, we are holding a reference to it so ownership applies! ## Iterating over the Values in a Vector We can use the loops we learned previously: ```rust let mut v = vec![100,32,57]; for i in &mut v{ *i += 50; // Dereferencing to modify the value } ``` ## Storing Multiple types in an Enum Enums are defined as a single type, but each value in an enum can hold different data. Then we can define a Vector that uses an Enum Type as its Generic, then we can use the enum values to store different types of values inside the Vector! ```rust enum SpreadsheetCell{ Int(i32), Float(f64), Text(String), } let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ] ``` This is similar to a `void*` vector, each type is a pointer to a certain type of data in heap in different positions, but the vector holding these pointers is compact in heap.