3.1 rust vector

 

vec创建

use std::option::Option::*;

fn main() {
    println!("---------------------------------------------");
    test_vec1();
    test_vec2();
}


fn test_vec1(){
    //let v: Vec<i32> = Vec::new();
    let mut v1 = Vec::new();
    v1.push(1);
    v1.push(2);
    v1.push(3);

    println!("{:?}",v1);

    let v2 = vec![4,5,6,];
    println!("{:?}",v2);
   
}


fn test_vec2(){
    let v = vec![1,2,3,4];
    let third: &i32 = &v[2];

    //The third element is 3
    println!("The third element is {}",third);

    match v.get(2) {
        Some(third) => println!("The third element is {}",third),
        None => println!("There is no third element."),
    }
}

 

$ cargo run
   Compiling aa_vec v0.1.0 (/opt/wks/rust_study/aa_vec)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30s
     Running `target/debug/aa_vec`
---------------------------------------------
[1, 2, 3]
[4, 5, 6]
The third element is 3
The third element is 3

 

vector 下标越界

fn test_vec3(){
    let v = vec![1,2,3];
    let not1 = v.get(10);
    println!("{:?}",not1);
}


fn test_vec4(){
    let v = vec![1,2,3];
    let not1 = v.get(10);
    let not2 = &v[10];
    println!("{:?}",not1);
    println!("{:?}",not2);
}

第一个方法会输出

None


第二个方法输出

thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 10', src/main.rs:54:17
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

 

引用注意事项

fn main() {
    let mut v = vec![1, 2, 3, 4, 5];

    let first = &v[0];

    v.push(6);

    println!("The first element is: {}", first);
}
$ cargo run
   Compiling collections v0.1.0 (file:///projects/collections)
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
 --> src/main.rs:6:5
  |
4 |     let first = &v[0];
  |                  - immutable borrow occurs here
5 | 
6 |     v.push(6);
  |     ^^^^^^^^^ mutable borrow occurs here
7 | 
8 |     println!("The first element is: {}", first);
  |                                          ----- immutable borrow later used here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0502`.
error: could not compile `collections`.

To learn more, run the command again with --verbose.

why should a reference to the first element care about what changes at the end of the vector? This error is due to the way vectors work: adding a new element onto the end of the vector might require allocating new memory and copying the old elements to the new space, if there isn’t enough room to put all the elements next to each other where the vector currently is. In that case, the reference to the first element would be pointing to deallocated memory. The borrowing rules prevent programs from ending up in that situation.

 正确的方式

fn test_vec5(){
    let mut v = vec![1, 2, 3, 4, 5];

    //第一次可变引用开始
    let first = &mut v[0];
    println!("The first element is: {}", first);

    //第一次可变引用消失
    //第二次可变引用开始
    v.push(6);
}

rust中,同一时刻,同时作用域中,可变引用只能有一处

 

for 循环遍历

pub fn for1(){
    println!("{}","---------------for 循环遍历-------------------");


    let list1 = vec![1,3,5,7];
    for v in &list1 {
        println!("{}",v);
    }

    let mut list2 = vec![2,4,6,8];
    for v in &mut list2 {
        *v += 10;
    }

    println!("{:?}",list2);

}

 输出

---------------for 循环遍历-------------------
1
3
5
7
[12, 14, 16, 18]

 

pub fn select_sort_vec_test() {
    let mut v1 = vec![1, 3, 2];
    select_sort_vec(&mut v1);
}

pub fn select_sort_vec(v1: &mut Vec<i32>){

    for (i,val) in v1.iter().enumerate() {
        println!("{}:{}",i,val);
        // 0:1
        // 1:3
        // 2:2
    }

    let le = v1.len();
    for i in 0..le {
        println!("{:?}",v1.get(i));
        // Some(1)
        // Some(3)
        // Some(2)
    }
}

 

 

 

使用枚举存放不同的类型的值

#[derive(Debug)]
enum DataType {
    Int(i32),
    Float(f64),
    Text(String),
}

fn test_vec6(){
    println!("{}","----------------------------------");
    let mut row = vec![
        DataType::Int(18),
        DataType::Float(1.23),
        DataType::Text(String::from("how ")),
        DataType::Text(String::from("are ")),
    ];

   
    let a = row.pop();
    println!("element:{:#?}",a);

     //
     row.push(DataType::Int(20));

    for r in &row {
        println!("{:#?}",r);
    }

}

输出

----------------------------------
element:Some(
    Text(
        "are ",
    ),
)
Int(
    18,
)
Float(
    1.23,
)
Text(
    "how ",
)
Int(
    20,
)

 

Vec修改

pub fn select_sort_vec(v1: &mut Vec<i32>){
    let le = v1.len();
    for i in 0..le {
        if let Some(elem) = v1.get_mut(i) {
            *elem = *elem + 1;
        }
    }
}

pub fn select_sort_vec_test() {
    let mut v1 = vec![1, 3, 2];
    select_sort_vec(&mut v1);

    for (i,val) in v1.iter().enumerate() {
        println!("{}:{}",i,val);
    }
}

 

一个vec中的数据类型必须相同

 let a = vec![1,"a"];
    |                    ^^^ expected integer, found `&str`

 

 

 

Vec其他用法 

 

posted @ 2020-08-13 12:53  方诚  阅读(219)  评论(0)    收藏  举报