Trust learning — using vectors to store value list

Time:2021-3-4

Vectors allow us to store multiple values in a single data structure, which places all values adjacent to each other in memory. Vectors can only store values of the same type. They are useful when we have a list of items, such as lines of text in a file or prices for items in a shopping cart.

Create a new vector

fn main() {
    let v: Vec<i32> = Vec::new();
    println!("{:?}", v)
}
D:\learn\cargo_learn>cargo run
   Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
    Finished dev [unoptimized + debuginfo] target(s) in 1.06s
     Running `target\debug\cargo_learn.exe`
[]

You can see that vector is actually an array, but there is a requirement that every element in the array must have the same type. Create a real instance as follows:

fn main() {
    let v = vec![1, 2, 3];
    println!("{:?}", v);
}
D:\learn\cargo_learn>cargo run
   Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
    Finished dev [unoptimized + debuginfo] target(s) in 0.52s
     Running `target\debug\cargo_learn.exe`
[1, 2, 3]

What happens if you don’t use the same type of data?

fn main() {
    let v = vec![1, 2.1, 3];
    println!("{:?}", v);
}

D:\learn\cargo_learn>cargo run
   Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
error[E0308]: mismatched types
 --> src\main.rs:2:21
  |
2 |     let v = vec![1, 2.1, 3];
  |                     ^^^ expected integer, found floating-point number

error: aborting due to previous error

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

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

Update a vector
In trust, no matter what variables are updated, they must be mutable

fn main() {
    let mut v = Vec::new();

    v.push(5);
    v.push(6);
    v.push(7);
    v.push(8);
    println!("{:?}", v)
}
D:\learn\cargo_learn>cargo run
   Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
    Finished dev [unoptimized + debuginfo] target(s) in 0.57s
     Running `target\debug\cargo_learn.exe`
[5, 6, 7, 8]

It can be seen that there is no difference with the array in JS, at least in using the push method~~

Delete a vector

Like ordinary variables in trust, vector is also a variable, which will be automatically cleaned up after it exceeds its scope, for example:

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

        //Here you can use V to do anything you want and can
    }// < - V out of range and released here
}

Reading elements in a vector

There are two ways to get elements in a vector: index and get

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

    let third: &i32 = &v[2];
    Println! (the third element is: {} ", third);

    match v.get(2) {
        Some (third) = > println,
        None = > println! ("the third element does not exist"),
    }
}

D:\learn\cargo_learn>cargo run
   Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
    Finished dev [unoptimized + debuginfo] target(s) in 0.52s
     Running `target\debug\cargo_learn.exe`
The third element is: 3
The third element is: 3

If the index value is used directly, if the index value exceeds the length range of the vector (0 ~ length – 1), it will lead to compilation or running errors. Using the get method can safely obtain elements and catch exceptions.

The get method can be simpler, for example:

 let does_not_exist = v.get(100);

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

At this point, if the index exceeds the range of the vector that can be indexed, it will be returnedNone

Interestingly, if you don’t pay attention, you will still encounter the phenomenon of ownership

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

    let first = &v[0];

    v.push(6);

    println!("The first element is: {}", first);
}

D:\learn\cargo_learn>cargo run
   Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
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 `cargo_learn`.

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

Traversing the values in a vector

1. General traversal, and print out all the values in the vector

fn main() { 
    let v = vec![100, 32, 57];
    for i in &v {
        println!("{}", i);
    }
}

2. Traverse and change the values in the vector according to certain rules

fn main() {
    let mut v = vec![100, 32, 57];
    for i in &mut v {
        *i += 50;
    }
}

To change the value referenced by a variable reference, you must first use the dereference operator (*) to get the value in I before using the + = operator.

Using enumeration to store multiple types
In rust, the variants of enumeration are defined under the same enumeration type, so when we need to store different types of elements in the vector, we can define and use enumeration! For example:

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

    let row = vec![
        SpreadsheetCell::Int(3),
        SpreadsheetCell::Text(String::from("blue")),
        SpreadsheetCell::Float(10.12),
    ];

    println!("{:?}", row)
}

D:\learn\cargo_learn>cargo run
   Compiling cargo_learn v0.1.0 (D:\learn\cargo_learn)
    Finished dev [unoptimized + debuginfo] target(s) in 0.63s
     Running `target\debug\cargo_learn.exe`
[Int(3), Text("blue"), Float(10.12)]

It can also be understood that the reason why it works is that enumeration is stored in vector as a type