LoginSignup
49
27

More than 3 years have passed since last update.

Rustにおける連想配列リテラル・ハッシュリテラル相当

Posted at

いろいろな言語の連想配列系リテラル記法を比較してみた | TechRacho という記事でRustにも言及されていますが、そこでは以下のような手続き的な構成が紹介されています。

use std::collections::HashMap;

let mut hash = HashMap::new();
hash.insert("apple".to_owned(), 1);
hash.insert("orange".to_owned(), 2);
hash.insert("coffee".to_owned(), 42);

Rustでこのように指定した値の入ったハッシュを作る場合、以下のように書くほうが好まれるかと思います。

use std::collections::HashMap;

let hash = vec![
    ("apple".to_owned(), 1),
    ("orange".to_owned(), 2),
    ("coffee".to_owned(), 42),
]
.into_iter()
.collect::<HashMap<_, _>>();

(Add IntoIterator impl for arrays by valueがマージされれば上記の vec![][] とすることができます)

また maplit クレート が以下のようなマクロを提供しています。

use maplit::hashmap;

let hash = hashmap!{
    "apple".to_owned() => 1,
    "orange".to_owned() => 2,
    "coffee".to_owned() => 42,
};

Rustのマクロは () [] {} のいずれでも呼び出せるので、 hashmap!()hashmap![] のように書いてもかまいません。 ({} だけ構文上の扱いが少しだけ異なりますが、このユースケースではほとんど問題にならないと思われます)

また本題とは逸れますが、上記のように String 型のリテラルが必要な場合は big_s クレート も便利です。

use big_s::S;
use maplit::hashmap;

let hash = hashmap![
    S("apple") => 1,
    S("orange") => 2,
    S("coffee") => 42,
];
49
27
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
27