##### 标题：Rust向量

• 向量用于存储相同类型的值。
• 矢量由`Vec <T>`表示。
• `Vec <T>`由标准库提供，它可以保存任何类型的数据，其中`T`确定向量的类型。
• 向量的数据在堆上分配。
• 向量是一个可增长的数组意味着可以在运行时添加新元素。

`Vec <T>` ：当向量保持特定类型时，它在角括号中表示。

## 如何创建向量？

``````Let v : Vec<i32> = Vec::new();
``````

Rust提供`vec!` 用于创建向量并保存提供的值的宏。

``````let v = vec![10,20,30,40,50];
``````

``````let v = vec![2 ; i];
``````

## 访问元素

``````fn main()
{
let v =vec![20,30,40,50];
println!("first element of a vector is :{}",v[0]);
println!("Second element of a vector is :{}",v[1]);
println!("Third element of a vector is :{}",v[2]);
println!("Fourth element of a vector is :{}",v[3]);
}
``````

``````first element of a vector is :20
Second element of a vector is :30
Third element of a vector is :40
Fourth element of a vector is :50
``````

``````fn value(n:Option<&i32>)
{
match n
{
Some(n)=>println!("Fourth element of a vector is {}",n),
None=>println!("None"),
}
}
fn main()
{
let v =vec![20,30,40,50];
let a: Option<&i32>=v.get(3);
value(a);
}
``````

``````Fourth element of a vector is 50
``````

## []和get()方法的区别：

• get(index)函数
``````fn value(n:Option<&i32>)
{
match n
{
Some(n)=>println!("Fourth element of a vector is {}",n),
None=>println!("None"),
}
}
fn main()
{
let v =vec![20,30,40,50];
let a: Option<&i32>=v.get(7);
value(a);
}
``````

``````None
``````
• []运算符
``````fn main()
{
let v =vec![20,30,40,50];
println!("{}",v[8]);
}
``````

## 迭代向量中的值

``````fn main()
{
let v =vec![20,30,40,50];
print!("Elements of vector are :");
for i in v
{
print!("{} ",i);
}
}
``````

``````Elements of vector are :20 30 40 50
``````

``````fn main()
{
let mut v =vec![20,30,40,50];
print!("Elements of vector are :");
for i in &mut v
{
*i+=20;
print!("{} ",i);
}
}
``````

``````Elements of vector are :20 30 40 50
``````

## 更新矢量

``````fn main()
{
let mut v=Vec::new();
v.push('j');
v.push('a');
v.push('v');
v.push('a');
for i in v
{
print!("{}",i);
}
}
``````

``````java
``````

## 删除矢量

``````fn main()
{
let v = !vec[30,40,50];
} # => v 在这里被释放，因为它超出了范围。
``````

## 使用Enum存储多种类型

``````#[derive(Debug)]
enum Values {
A(i32),
B(f64),
C(String),
}

fn main()
{
let v = vec![Values::A(5),
Values::B(10.7),Values::C(String::from("Yiibai"))];
for i in v
{
println!("{:?}",i);
}
}
``````

``````A(5)
B(10.7)
C(Yiibai)
``````

• Rust在编译时知道向量元素的类型，以确定每个元素需要多少内存。
• 当向量由一个或多个类型的元素组成时，对元素执行的操作将导致错误，但使用带有匹配的枚举将确保可以在运行时处理每个可能的情况。