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

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.

主站蜘蛛池模板: 岳池县| 东宁县| 商都县| 南江县| 南召县| 杭锦旗| 织金县| 霞浦县| 双柏县| 东山县| 宁武县| 巫山县| 巢湖市| 右玉县| 洛南县| 昌江| 边坝县| 荆州市| 鄂托克旗| 威远县| 石楼县| 深圳市| 油尖旺区| 佛冈县| 柳林县| 泰来县| 建平县| 金华市| 巴里| 贺州市| 和平区| 和林格尔县| 集贤县| 永嘉县| 永康市| 阿瓦提县| 高密市| 东阳市| 于田县| 思南县| 什邡市|