Consider the following Rust code that adds elements to a vector. What will be printed?
fn main() {
let mut v = Vec::new();
v.push(10);
v.push(20);
v.push(30);
println!("{:?}", v);
}Remember that push adds elements to the end of the vector.
The push method appends elements to the end of the vector, so the vector contains [10, 20, 30].
What error or output results from this Rust code?
fn main() {
let v = Vec::new();
v.push(5);
println!("{:?}", v);
}Think about whether the vector is mutable or not.
The vector v is not declared mutable, so calling push causes a compile-time error.
Examine the code below. Why does it fail to compile?
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("first element: {}", first);
}Think about Rust's borrowing rules when mixing mutable and immutable references.
The immutable borrow first is active when v.push(4) tries to mutably borrow v, causing a compile-time error.
Given the following Rust code, what is the length of the vector v after execution?
fn main() {
let mut v = Vec::with_capacity(5);
v.push(1);
v.push(2);
v.push(3);
v.pop();
v.push(4);
println!("{}", v.len());
}Remember that pop removes one element from the vector.
After pushing 3 elements, length is 3. pop removes one, length becomes 2. Then pushing one more makes length 3.
Why can vectors in Rust grow dynamically when elements are added with push?
Think about how memory allocation works for vectors in Rust.
Vectors allocate more memory than needed initially and reallocate to a larger buffer when capacity is exceeded, allowing dynamic growth.
