0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RustでRubyのハッシュを実現する

Last updated at Posted at 2023-03-10

RustでRubyのハッシュを実現する

Rust初心者が、Rubyのようなハッシュ形式でデータを扱おうとすると苦戦しました。結論は一番下にある。

やりたいこと

Rubyのように変数名.キー(ここではuser.name)という形で値を取得したい。

user = { "name": "Shohei", "age": 27 }
user.name // => "Shohei"

背景

Rustのハッシュマップを使ってもうまくいかない。

パターン1

ハッシュマップを使ってやってみる。

fn main() {
    let mut user = HashMap::new();
    user.insert("name", "Shohei");
    println!("{:?}", user["name"]); // => "Shohei"

    let mut user = HashMap::new();
    user.insert("age", 28);
    println!("{:?}", user["age"]); // => 28
}

これじゃあ、nameとageが別の変数として扱われる。配列みたいに、データをまとめて保存したい。

パターン2

ハッシュマップ + タプルを使ってみる。

use std::collections::HashMap;

fn main() {
    let mut user = (HashMap::new(), HashMap::new());

    user.0.insert("name", "Shohei");
    user.1.insert("age", 28);

    println!("{:?}", user); // ( {"name": "Shohei"}, {"age": 28} )
    println!("{:?}", user.0["name"]); // "Shohei"
    println!("{:?}", user.1["age"]); // 28
}

なんとかデータをまとめることができた。
しかしユーザーネームを取得する時の、user.0[”name”]の0が邪魔。
しかもageを取得する時は1に変えないとダメ。

結論

構造体を使えばいい。

fn main() {
    let user = User{
        name: String::from("Shohei"),
        age: 28,
    };

    println!("{:?}", user); // User { name: "Shohei", age: 28 }
    println!("{:?}", user.name); // "Shohei"
    println!("{:?}", user.age); // 28
}

#[derive(Debug)] // これつけないとuserを出力できない。
struct User {
    name: String,
    age: u8,
}

データもまとめられているし、可読性もいい感じ。構造体ってこんなふうに使うんだと、勉強になった。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?