官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 临海市| 加查县| 连山| 永定县| 安泽县| 吴忠市| 万载县| 手游| 德安县| 娄烦县| 湖北省| 玛纳斯县| 永新县| 垫江县| 西乡县| 西平县| 梁河县| 呼玛县| 浦北县| 浪卡子县| 乌苏市| 太谷县| 沾化县| 怀集县| 金昌市| 安康市| 眉山市| 怀柔区| 镇原县| 卓尼县| 始兴县| 资阳市| 临澧县| 宜昌市| 洛阳市| 沂水县| 芜湖县| 靖江市| 密山市| 通州区| 昌都县|