Article directory
foreword
Rust common collections also contain Vector
containers, 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,
Vector
a 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
- Using the Vec::new function
- Example:
let v: Vec<i32> = Vec::new();//需指定类型如 i32
- Although Rust has powerful type inference capabilities, we
Vec::new
can only create an emptyvector
container
without taking the next step, then we need to explicitly declare the data type.
- 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
push
method- Example:
let mut v = Vec::new(); v.push(6); v.push(2); // 这里不需要显示声明类型,因为创建后又添加了元素值。
- Note that
v
the keyword is added beforemut
, 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)
- read element by index
- by
get
method - 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
- difference between the two
- When the index exceeds the current array length, it will cause a
painc
panic, and the program will crash and abort. - When out of bounds using
match
the method paired withget
, it will be printedNull
and the program will not be aborted.
- When the index exceeds the current array length, it will cause a
2.4. Traverse the values in the Vector
- Use a
for
loop: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
python
is exactly the same as the for loop of , but if you want to operate on the element values, you must declarev
it as a variable variable, andin
then you need to add&mut
a variable reference, here*i
is each index The corresponding value can be understood asc++
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
Vector
also 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 borrowv
as mutable because it is also borrowed as immutable
- English means you can't make
v
a lease as a mutable reference because it's already immutable - In fact, this has something to do with
Vector
the dynamic memory in the working principle. If the container re-allocates space for the element value,first
but it is an immutable reference, the first value at this time is meaningless.
- English means you can't make
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:
Virous
is a defined enum class with three types of variants:i32
,f64
,String
print_all
The function has no return, the parameter is a collection that stores the Virous enumeration type , and theVector
function is to traverse and print- The main function is to define variables
v
and initialize four element values, all three types are involved, and finally call the function to complete the operation
running result:
有关Rust常用集合Rust的分享就到此结束了,后续将会带来另外的常用集合。觉得写的不错可以点赞鼓励博主,给我不断更文的动力!