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
4
let mut v1 = vec![1,2,3];
let item = v1[0];
println!("{:?},{:?}", v1.get(0),v1.get(100));
//Some(1),None

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;

insert

1
2
3
4
5
6
fn main() {
    let mut v1 = vec![1,2,3];
    v1.insert(2,1);
    println!("v1:{:?}",v1);
}
// v1:[1, 2, 1, 3]

remove

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

append

1
2
3
4
5
6
7
fn main() {
    let mut v1 = vec![1,2,3];
    let mut v2 = vec![4,5,6];
    v1.append(&mut v2);
    println!("v1:{:?}",v1);
}
// v1:[1, 2, 3, 4, 5, 6]

sort

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
fn main() {
    let mut v1 = vec![1,2,3, 3,2,1];
    
    v1.sort();
    
    println!("v1:{:?}",v1);
    let result = v1.binary_search(&2);
    
    println!("result:{:?}",result);
}
// v1:[1, 1, 2, 2, 3, 3]
// result:Ok(3)

resize

1
2
3
4
5
6
7
8
9
fn main() {
    let mut v1 = vec![1,2,3, 3,2,1];
    v1.resize(10, 0);
    println!("v1:{:?}",v1);
    v1.resize(2, 0);
    println!("v1:{:?}",v1);
}
// v1:[1, 2, 3, 3, 2, 1, 0, 0, 0, 0] 
// v1:[1, 2]

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());

is_empty

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

contains

1
2
3
4
5
6
7
8
9
fn main() {
    let mut v1 = vec![1,2,3];
    
    println!("{} is in v1:{:?}",1, v1.contains(&1));
    
    println!("{} is in v1:{:?}",11, v1.contains(&11));
}
// 1 is in v1:true 
// 11 is in v1:false