C10: std::Vector Flashcards

1
Q

Creating a new, empty vector to hold values of type i32

A
 let v: Vec<i32> = Vec::new();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Vector puts all the values next to each other in memory?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Vectors can only store values of the same type?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Creating a new vector containing values

A

let v = vec![1, 2, 3];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Updating a Vector

A

let mut v = Vec::new();

v.push(5);
v.push(6);
v.push(7);
v.push(8);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Reading Elements of Vectors

A

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."),
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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}");
A

$ 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Iterating over the Values in a Vector

A

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;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Using an Enum to Store Multiple Types in a Vector

A

enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}

let row = vec![
    SpreadsheetCell::Int(3),
    SpreadsheetCell::Text(String::from("blue")),
    SpreadsheetCell::Float(10.12),
];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly