create

不指定数据类型

1
2
let mut v1 = Vec::new();  
let mut v2 = vec![];

指定数据类型

1
2
3
let mut v1:Vec<i32> = Vec::new();
let mut v2:Vec<i32> = vec![];
let mut v3 = vec![1i32, 2,3];

创建并初始化

1
2
3
4
5
let mut v1 = vec![1,2,3];
let mut v2:Vec<i32> = vec![1,2,3];
let mut v3 = vec![1i32,2,3];
let mut v4 = vec![1; 10];
let mut v5: Vec<i32> = (0..10).collect();

访问元素

1
2
3
let mut v1 = vec![1,2,3];
let item = v1[0];
println!("v1={:?}",v1);

slice

1
2
3
let v1 = vec![1,2,3,4,5];
let v2 = v1[1..];
let v2 = v1[1..3];

1
2
let mut v1 = vec![1,2,3];
v1[0] = 11;

push and pop

1
2
3
4
let mut v1 = vec![1,2,3];
v1.push(4);
v1.push(5);
let item = v1.pop();

iterator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let mut v = vec![1,2,3];

for item in &v {

}

for itme in &mut v {

}

for item in v {

}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let mut v = vec![1,2,3];
for (i, x) in v.iter().enumerate() {
        println!("In position {} we have value {}", i, x);
}

for x in v.iter() {
       println!("item:{}",x); 
}

for x in v.iter_mut() {
        *x *= 3;
}
println!("Updated vector: {:?}", xs);
1
2
3
let items = vec![1, 2, 3];
let sitems = items.into_iter().map(|x| x.to_string()).collect::<Vec<_>>();
println!("sitem: {:?}",sitems);

属性

capacity

1
2
let mut v1 = vec![1,2,3];
println!("capacity={}",v1.capacity());

len

1
2
let mut v1 = vec![1,2,3];
println!("len={}",v1.len());