[][src]Function tao_of_rust::ch02::collections::vec_example

pub fn vec_example()

线性序列:向量(Vec)

Basic usage:

fn vec_example(){
    let mut v1 = vec![];
    v1.push(1);  // 使用push方法插入元素
    v1.push(2);
    v1.push(3);
    assert_eq!(v1, [1,2,3]);
    assert_eq!(v1[1], 2);
    let mut v2 = vec!["hello".to_string(); 10];  // 像数组那样初始化
    assert_eq!(v2.len(), 10);
    assert_eq!(v2[5], "hello".to_string());
    let mut v3 = Vec::new();
    v3.push(4);
    v3.push(5);
    v3.push(6);
    // v3[4];  error: index out of bounds
}
vec_example();Run