◾️はじめに
今回は、Rustの配列・コレクションに関して扱う (もう少しで基礎的なことが終わる、、、)
目次
【1】複合型 1)配列 2)タプル 【2】ベクタ型 1)Vec型 2)HashMap型 3)HashSet型
【1】複合型
* 2種類の基本的な複合型がある [1] 配列 [2] タプル
https://doc.rust-jp.rs/book-ja/ch03-02-data-types.html
1)配列
* 普通のプログラムと変わらない
例
fn main() { let array = [1, 2, 3, 4, 5]; println!("{}", array[0]); // 1 for &item in &array { println!("{}", item); // 1 2 3 4 5 } }
2)タプル
* こっちも、Pythonなどの他のプログラムとほぼ変わらない => 複数の型を一つの複合型にまとめ上げる
例
fn main() { let tuple = ("Mike", 30, true); println!("{}", tuple.0); // Mike println!("{}", tuple.1); // 30 println!("{}", tuple.2); // true let (name, age, is_student) = tuple; println!("Name: {}", name); // Mike println!("Age: {}", age); // 30 println!("Is Student: {}", is_student); // true }
【2】ベクタ型
| 種類 | 説明 | メモ |
|---|---|---|
| スカラー型 | 1つの値を扱う型 | 整数など |
| ベクタ型 | 複数の値を保管し動的に変更可能な型 | ここでのテーマ |
1)Vec型
* サイズを変更可能な配列
https://doc.rust-jp.rs/rust-by-example-ja/std/vec.html
例1:空のVecを作成するには
let demo_vecs = Vec::new(); let demo_vec2s = Vec::new<i32>();
例2:初期値を待つVecを作成するには
let init_vecs: Vec<i32> = vec![1, 2, 3];
例3:値の追加(push)と取り出し(get)には
fn main() { let mut init_vecs: Vec<i32> = vec![1, 2, 3]; // Add init_vecs.push(4); // Get println!("{:?}", init_vecs.get(0).unwrap()); // 1 println!("{:?}", init_vecs[2]); // 3 println!("**********"); for v in &init_vecs { println!("{}", v); } }
例4:値の挿入(insert)と削除(remove)には
fn main() { let mut init_vecs: Vec<i32> = vec![1, 2, 3]; // Insert init_vecs.insert(0, 0); init_vecs.insert(3, 99); // 0,1,2,99,3 // Get println!("{:?}", init_vecs.get(0).unwrap()); // 0 println!("{:?}", init_vecs[3]); // 99 // Remove init_vecs.remove(4); // 0,1,2,99,3 -> 0,1,2,99 println!("**********"); for v in &init_vecs { println!("{}", v); // 0 1 2 99 } }
2)HashMap型
* 辞書型(キー/バリュー型)
例
use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert("key1", "value1"); map.insert("key2", "value2"); map.insert("key3", "value3"); map.remove("key2"); for (key, value) in &map { println!("{}: {}", key, value); } }
3)HashSet型
* 値がなくキーのみのHashMap => 重複なしの配列(順不同)
例
use std::collections::HashSet; fn main() { let mut set = HashSet::new(); set.insert("value1"); set.insert("value2"); set.insert("value3"); set.insert("value1"); set.insert("value4"); set.remove("value2"); for value in &set { println!("{}", value); // value3 value4 value1 (in any order) } }
参考文献
https://qiita.com/garkimasera/items/a6df4d1cd99bc5010a5e
関連記事
Rust ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/04/22/234808
Rust ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2025/11/26/224648
Rust ~ 変数 / データ型 ~
https://dk521123.hatenablog.com/entry/2025/12/05/000647