# 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在編譯時知道向量元素的型別，以確定每個元素需要多少記憶體。
• 當向量由一個或多個型別的元素組成時，對元素執行的操作將導致錯誤，但使用帶有匹配的列舉將確保可以在執行時處理每個可能的情況。