# Vectors
> [vectors.md](https://github.com/rust-lang/rust/blob/master/src/doc/book/vectors.md)
commit 5b9dd6a016adb5ed67e150643fb7e21dcc916845
“Vector”是一個動態或“可增長”的數組,被實現為標準庫類型[`Vec<T>`](http://doc.rust-lang.org/std/vec/)(其中`<T>`是一個[泛型](#)語句)。vector總是在堆上分配數據。vector與切片就像`String`與`&str`一樣。你可以使用`vec!`宏來創建它:
~~~
let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>
~~~
(與之前使用`println!`宏時不一樣,我們用中括號`[]`配合`vec!`。為了方便,Rust 允許使用上述各種情況。)
對于重復初始值有另一種形式的`vec!`:
~~~
let v = vec![0; 10]; // ten zeroes
~~~
### 訪問元素
為了vector特定索引的值,使用`[]`:
~~~
let v = vec![1, 2, 3, 4, 5];
println!("The third element of v is {}", v[2]);
~~~
索引從`0`開始,所以第3個元素是`v[2]`。
另外值得注意的是必須用`usize`類型的值來索引:
~~~
let v = vec![1, 2, 3, 4, 5];
let i: usize = 0;
let j: i32 = 0;
// works
v[i];
// doesn’t
v[j];
~~~
用非`usize`類型索引的話會給出類似如下的錯誤:
~~~
error: the trait `core::ops::Index` 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
~~~
信息中有很多標點符號,不過關鍵是:你不能用`i32`來索引。
### 越界訪問(Out-of-bounds Access)
如果嘗試訪問并不存在的索引:
~~~
let v = vec![1, 2, 3];
println!("Item 7 is {}", v[7]);
~~~
那么當前的線程會 [panic](#)并輸出如下信息:
~~~
thread '' panicked at 'index out of bounds: the len is 3 but the index is 7'
~~~
如果你想處理越界錯誤而不是 panic,你可以使用像[`get`](http://doc.rust-lang.org/std/vec/struct.Vec.html#method.get)或[`get_mut`](http://doc.rust-lang.org/std/vec/struct.Vec.html#method.get)這樣的方法,他們當給出一個無效的索引時返回`None`:
~~~
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.")
}
~~~
### 迭代
可以用`for`來迭代 vector 的元素。有3個版本:
~~~
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);
}
~~~
vector還有很多有用的方法,可以看看[vector的API文檔](http://doc.rust-lang.org/nightly/std/vec/)了解它們。
- 前言
- 貢獻者
- 1.介紹
- 2.準備
- 3.學習 Rust
- 3.1.猜猜看
- 3.2.哲學家就餐問題
- 3.3.其它語言中的 Rust
- 4.語法和語義
- 4.1.變量綁定
- 4.2.函數
- 4.3.原生類型
- 4.4.注釋
- 4.5.If語句
- 4.6.循環
- 4.7.所有權
- 4.8.引用和借用
- 4.9.生命周期
- 4.10.可變性
- 4.11.結構體
- 4.12.枚舉
- 4.13.匹配
- 4.14.模式
- 4.15.方法語法
- 4.16.Vectors
- 4.17.字符串
- 4.18.泛型
- 4.19.Traits
- 4.20.Drop
- 4.21.if let
- 4.22.trait 對象
- 4.23.閉包
- 4.24.通用函數調用語法
- 4.25.crate 和模塊
- 4.26.const和static
- 4.27.屬性
- 4.28.type別名
- 4.29.類型轉換
- 4.30.關聯類型
- 4.31.不定長類型
- 4.32.運算符和重載
- 4.33.Deref強制多態
- 4.34.宏
- 4.35.裸指針
- 4.36.不安全代碼
- 5.高效 Rust
- 5.1.棧和堆
- 5.2.測試
- 5.3.條件編譯
- 5.4.文檔
- 5.5.迭代器
- 5.6.并發
- 5.7.錯誤處理
- 5.8.選擇你的保證
- 5.9.外部函數接口
- 5.10.Borrow 和 AsRef
- 5.11.發布途徑
- 5.12.不使用標準庫
- 6.Rust 開發版
- 6.1.編譯器插件
- 6.2.內聯匯編
- 6.4.固有功能
- 6.5.語言項
- 6.6.鏈接進階
- 6.7.基準測試
- 6.8.裝箱語法和模式
- 6.9.切片模式
- 6.10.關聯常量
- 6.11.自定義內存分配器
- 7.詞匯表
- 8.語法索引
- 9.參考文獻
- 附錄:名詞中英文對照