# 向量

let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>


（注意到不像之前使用的 println! 巨集，vec! 巨集使用方括號，Rust 允許我們使用圓括號或方括號。 在這裡使用方括號純粹是慣例。）

vec! 有另一種用來產生重複初始值的形式：

let v = vec![0; 10]; // ten zeroes


## 存取物件

let v = vec![1, 2, 3, 4, 5];

println!("The third element of v is {}", v[2]);


let v = vec![1, 2, 3, 4, 5];

let i: usize = 0;
let j: i32 = 0;

// works
v[i];

// doesn’t
v[j];


error: the trait core::ops::Index<i32> is not implemented for the type
collections::vec::Vec<_> [E0277]
v[j];
^~~~
note: the type collections::vec::Vec<_> cannot be indexed by i32
error: aborting due to previous error


## 超出邊界存取

let v = vec![1, 2, 3];
println!("Item 7 is {}", v[7]);


thread '<main>' panicked at 'index out of bounds: the len is 3 but the index is 7'


let v = vec![1, 2, 3];
match v.get(7) {
Some(x) => println!("Item 7 is {}", x),
None => println!("Sorry, this vector is too short.")
}


## 疊代

let mut v = vec![1, 2, 3, 4, 5];

for i in &v {
println!("A reference to {}", i);
}

for i in &mut v {
println!("A mutable reference to {}", i);
}

for i in v {
println!("Take ownership of the vector and its element {}", i);
}


commit f2bea1c