[Rust Guide] Basic operations of common collection Vector | Combined with enum multi-type storage

insert image description here

  foreword

  Rust common collections also contain Vectorcontainers, which we are familiar with in other languages ​​such as C++, but there are not small differences in usage. The most typical is the impact of the lease rules on its role. This blog will introduce the commonly used collection Vector in Rust. If you learn it, you can fight against the Rust algorithm problem.


1. Vector storage features

Vec<T>called Vector, has the following characteristics:

  • Provided by the standard library to store multiple values
  • Only data of the same type can be stored, and element values ​​are stored continuously in memory
  • Element values ​​can be dynamically added at the end
    • Let's talk about how it works:
    • Dynamic addition not only means that the element value can be added at the end, but also because when the continuous memory block cannot meet the demand, Vectora large space of memory will be reallocated to store the value of each element, which is also called dynamic memory .

2. Vector basic operations

2.1. Create a Vector container

  1. Using the Vec::new function
    • Example:
    	let v: Vec<i32> = Vec::new();//需指定类型如 i32
    
    • Although Rust has powerful type inference capabilities, we Vec::newcan only create an empty vectorcontainer
      without taking the next step, then we need to explicitly declare the data type.
  2. Use the vec! macro
    • Here is a method created with initial values:
    	let v = vec![14,28,66];
    
    • There is no need to explicitly declare the type, the initial value can be automatically deduced by the compiler.

2.2, add element value

  • Add elements to the Vector, using the pushmethod
    • Example:
    	let mut v = Vec::new();
    	v.push(6);
    	v.push(2);
    	// 这里不需要显示声明类型,因为创建后又添加了元素值。
    
    • Note that vthe keyword is added before mut, because it is to add elements, it needs to be declared as a variable variable.

2.3, delete Vector

  • Like any other struct, the Vector is destroyed when it goes out of scope,
    and the values ​​of the elements in the container are cleaned up.
  • The deletion operation looks very simple and does not require our code operation,
    but if it involves references to the elements in it, the situation will be much more complicated, continue to look down.

2.3, read element value (reference)

  1. read element by index
  2. by getmethod
  3. Example:
    fn main() {
          
          
    	let v =vec![1,2,3,4,5,6];
    	let fourth = &v[3];
    	println!("The exact element is {}",fourth);
    
    	match v.get(3) {
          
          
        	Some(four)=>println!("The exact element is {}",four),
        	None => println!("Null")
    	}
    }
    //运行结果为两边:The exact element is 4
    
  4. difference between the two
    • When the index exceeds the current array length, it will cause a paincpanic, and the program will crash and abort.
    • When out of bounds using matchthe method paired with get, it will be printed Nulland the program will not be aborted.

2.4. Traverse the values ​​in the Vector

  • Use a forloop:
    fn main() {
          
          
        let  v = vec![10,24,30,50];
        for i in &v{
          
          
        	println!("{}",i);
      	}
    }
    //运行结果:10 24 30 50
    
  • Implement basic operations on each element
    fn main() {
          
          
    	let mut v= vec![10,24,30,50];
    	for i in &mut v{
          
          
     	  *i+=10;
    	   println!("{}",i);
       }
    }
    //运行结果:20 34 40 60
    

If it is to simply read all element values, the method pythonis exactly the same as the for loop of , but if you want to operate on the element values, you must declare vit as a variable variable, and inthen you need to add &muta variable reference, here *iis each index The corresponding value can be understood as c++the dereference method in .

3. Effects of ownership and borrowing rules

You cannot have both mutable and immutable references in the same scope

  • This rule Vectoralso holds in

  • Example

      fn main() {
          
          
      	  let mut v= vec![10,24,30,50];
      	  let first = &v[0];
      	  v.push(66);
          println!("{}",first);
      }
      //这是有问题的代码
    
  • 报错信息:
    error[E0502]: cannot borrow v as mutable because it is also borrowed as immutable
    insert image description here

    • English means you can't make va lease as a mutable reference because it's already immutable
    • In fact, this has something to do with Vectorthe dynamic memory in the working principle. If the container re-allocates space for the element value, firstbut it is an immutable reference, the first value at this time is meaningless.

4. Combined with enum to store multiple data types

Variants of enum can attach different types of data and are defined under the same enum type

Comprehensive example:

#[derive(Debug)] //配合{:?},输出枚举的变体
enum Virous {
    
    
    Int(i32),
    Float(f64),
    Text(String)
}
//用来输出Vector所有元素
fn print_all(v:Vec<Virous>){
    
    
    for v in &v{
    
    
        println!("{:?}",v);
    }
}
fn main() {
    
    
   let v= vec![
    Virous::Int(99),
    Virous::Text(String::from("微凉秋意")),
    Virous::Float(38.6),
    Virous::Float(66.6)];
    //调用函数
    print_all(v);
}

Code Explanation:

  • Virousis a defined enum class with three types of variants: i32, f64,String
  • print_allThe function has no return, the parameter is a collection that stores the Virous enumeration type , and the Vectorfunction is to traverse and print
  • The main function is to define variables vand initialize four element values, all three types are involved, and finally call the function to complete the operation

running result:

insert image description here


有关Rust常用集合Rust的分享就到此结束了,后续将会带来另外的常用集合。觉得写的不错可以点赞鼓励博主,给我不断更文的动力!

Guess you like

Origin blog.csdn.net/m0_58618795/article/details/127142428