Search⌘ K
AI Features

Solution Review: Resizing a Vector

Explore how to resize and manipulate Rust vectors by removing and adding elements using functions like pop, remove, and push. Learn to sum vector elements through iteration with for loops and prepare for understanding more complex Rust data structures like structs.

We'll cover the following...

Solution

Rust 1.40.0
fn test(my_vec: &mut Vec<u32>)-> &mut Vec<u32>{
let middle = (my_vec.len())/2;
my_vec.pop();
my_vec.remove(middle - 1);
let mut sum : u32 = 0;
for v in my_vec.iter()
{
sum = sum + v;
}
my_vec.push(sum);
my_vec
}
fn main(){
let mut v1 = vec![1, 5, 7, 9];
println!("Original Vector: {:?}", v1);
println!("Updated Vector: {:?}", test(&mut v1));
let mut v2 = vec![1, 2, 3, 1, 2, 6];
println!("Original Vector: {:?}", v2);
println!("Updated Vector: {:?}", test(&mut v2));
}

Explanation

A function test ...