ベクタ型
Vectors are re-sizable arrays. Like slices, their size is not known at compile time, but they can grow or shrink at any time. A vector is represented using 3 parameters:
- データへのポインタ
- 長さ
- capacity
The capacity indicates how much memory is reserved for the vector. The vector can grow as long as the length is smaller than the capacity. When this threshold needs to be surpassed, the vector is reallocated with a larger capacity.
fn main() { // イテレータは要素を収集してベクタにすることができます。 let collected_iterator: Vec<i32> = (0..10).collect(); println!("Collected (0..10) into: {:?}", collected_iterator); // ベクタの初期化には`vec!`マクロが使用できます。 let mut xs = vec![1i32, 2, 3]; println!("Initial vector: {:?}", xs); // 新しい要素をベクタの最後に挿入することができます。 println!("Push 4 into the vector"); xs.push(4); println!("Vector: {:?}", xs); // エラー!イミュータブルなベクタは成長できません collected_iterator.push(0); // FIXME ^ この行をコメントアウトしましょう // `len`メソッドは現在のベクタのサイズを返します。 println!("Vector length: {}", xs.len()); // 鍵括弧を用いてインデックスによる要素へのアクセスができます。 // (インデックスは0から開始する) println!("Second element: {}", xs[1]); // `pop`はベクタの最後の要素を削除すると同時に返します。 println!("Pop last element: {:?}", xs.pop()); // 不正なインデックスアクセスはpanicを引き起こします。 println!("Fourth element: {}", xs[3]); // FIXME ^ この行をコメントアウトしましょう // `Vector`は簡単にイテレートできます。 println!("Contents of xs:"); for x in xs.iter() { println!("> {}", x); } // `Vector`をイテレートしながら、 // イテレーションの回数を別の変数(`i`)に列挙することもできます。 for (i, x) in xs.iter().enumerate() { println!("In position {} we have value {}", i, x); } // `iter_mut`を使うと、ミュータブルな`Vector`をイテレートし、 // それぞれの値を修正することができます。 for x in xs.iter_mut() { *x *= 3; } println!("Updated vector: {:?}", xs); }
Vec
型のメソッドの一覧はstd::vecモジュールを見てください。