C10: std::Vector Flashcards
Creating a new, empty vector to hold values of type i32
let v: Vec<i32> = Vec::new();
Vector puts all the values next to each other in memory?
Yes
Vectors can only store values of the same type?
Yes
Creating a new vector containing values
let v = vec![1, 2, 3];
Updating a Vector
let mut v = Vec::new();
v.push(5); v.push(6); v.push(7); v.push(8);
Reading Elements of Vectors
let v = vec![1, 2, 3, 4, 5];
let third: &i32 = &v[2]; println!("The third element is {third}"); let third: Option<&i32> = v.get(2); match third { Some(third) => println!("The third element is {third}"), None => println!("There is no third element."), }
Does this work?
let mut v = vec![1, 2, 3, 4, 5]; let first = &v[0]; v.push(6); println!("The first element is: {first}");
$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0502]: cannot borrow v
as mutable because it is also borrowed as immutable
–> src/main.rs:6:5
|
4 | let first = &v[0];
| - immutable borrow occurs here
5 |
6 | v.push(6);
| ^^^^^^^^^ mutable borrow occurs here
7 |
8 | println!(“The first element is: {first}”);
| —– immutable borrow later used here
For more information about this error, try rustc --explain E0502
.
error: could not compile collections
due to previous error
The code in Listing 8-6 might look like it should work: why should a reference to the first element care about changes at the end of the vector? This error is due to the way vectors work: because vectors put the values next to each other in memory, adding a new element onto the end of the vector might require allocating new memory and copying the old elements to the new space, if there isn’t enough room to put all the elements next to each other where the vector is currently stored. In that case, the reference to the first element would be pointing to deallocated memory. The borrowing rules prevent programs from ending up in that situation.
Iterating over the Values in a Vector
let v = vec![100, 32, 57];
for i in &v {
println!(“{i}”);
}
let mut v = vec![100, 32, 57];
for i in &mut v {
*i += 50;
}
Using an Enum to Store Multiple Types in a Vector
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ];