--- id: 2eec2c96-e006-4a53-b5cc-fd39f466a6b7 title: Rust Vectors --- # Traits ## std ### convert - [TryInto](20201119171245-tryinto) # Description Vectors allow you to store more than one value in a single data structure that puts all the values next to each other in memory. Vectors can only store values of the same type. They are useful when you have a list of items, such as the lines of text in a file or the prices of items in a shopping cart. # Creating a New Vector ``` rust fn main() { let v: Vec = Vec::new(); } ``` ## vec! macro Rust can often infer the type of value you want to store in the Vector. For convenience one can also use the [vec! macro](https://doc.rust-lang.org/std/macro.vec.html). ``` rust fn main() { let v = vec![1, 2, 3]; } ``` # Updating a Vector ``` rust fn main() { let mut v = Vec::new(); v.push(5); v.push(6); v.push(7); v.push(8); } ``` # Dropping a Vector Like other [structs](20200831193417-structs), vectors are freed when they go out of scope, along with the vector contents: ``` rust fn main() { { let v = vec![1, 2, 3, 4]; // do stuff with v } // <- v goes out of scope and is freed here } ``` # Read Vector elements There are two ways to reference a value stored in a vector: ``` rust fn main() { let v = vec![1, 2, 3, 4, 5]; let third: &i32 = &v[2]; println!("The third element is {}", third); match v.get(2) { Some(third) => println!("The third element is {}", third), None => println!("There is no third element."), } } ``` Using [get](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.get) together with [match](https://doc.rust-lang.org/rust-by-example/flow_control/match.html) seems preferable, as trying to get non existant elements with method \#1 will cause an \`index out of bounds\` panic: ``` rust fn main() { let v = vec![1, 2, 3, 4, 5]; let does_not_exist = &v[100]; let does_not_exist = v.get(100); } ``` When the `get` method is passed an index that is outside the vector, it returns `None` without panicking. # Iteration ## Immutable references ``` rust fn main() { let v = vec![100, 32, 57]; for i in &v { println!("{}", i); } } ``` ## Mutable references ``` rust fn main() { let mut v = vec![100, 32, 57]; for i in &mut v { *i += 50; } } ``` # Using Enums to store multiple types ``` rust fn main() { enum SpreadsheetCell { Int(i32), Float(f64), Text(String), } let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ]; } ```