Adding and removing from the vector

In a similar fashion to string, it is possible to add and remove from the vector list using the push and pull methods. These add or remove from the top of the vector stack. Consider the following example:

fn main() { 
    let mut my_vec : Vec<i32> = (0..10).collect(); 
    println!("{:?}", my_vec);  
    my_vec.push(13); 
    my_vec.push(21); 
    println!("{:?}", my_vec);  
    let mut twenty_one = my_vec.pop(); // removes the last value 
    println!("twenty_one= {:?}", twenty_one);  
    println!("{:?}", my_vec);  
} 

We create the vector list with values from 0 going up to 10 (so the last value is 9).

The line println!("{:?}", my_vec); outputs the entire contents of my_vec. {:?} is required here due to the type Vec<i32> not implementing certain formatting functionalities.

We then push onto the top of the vector list 13 then 21, display the output on the screen, and then remove the top-most value on the vector list, and output it again.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset