Home > Software engineering >  How can I define HashMap literals with a level of concision similar to that of JSON in Rust?
How can I define HashMap literals with a level of concision similar to that of JSON in Rust?

Time:11-26

I want to initialize a Rust variable with a literal.

Shepmaster guesses that Rust has no map literal because:

the fact that there are multiple data structures that act maplike (such as both BTreeMap and HashMap) would make it hard to pick one.

But Rust says "you should probably just use Vec or HashMap", meaning that if they are good enough for most purposes, then using them when initializing from a string should usually work just fine.

The example map initialization is clumsy, but printing it produces the JSON-like string:

{"Mars": 1.5, "Mercury": 0.4, "Earth": 1.0, "Venus": 0.7}.

fn main() {
use std::collections::HashMap;

let solar_distance = HashMap::from([
    ("Mercury", 0.4),
    ("Venus", 0.7),
    ("Earth", 1.0),
    ("Mars", 1.5),
]);

println!("{:?}", solar_distance)
}

It shouldn't be technically impossible to create a Rust collection from a string literal (perhaps with syntactic sugar to avoid quote-escape hell) or by loading a JSON file, using the recommended types for arrays and objects:

fn main() {
use std::collections::HashMap;

let x = String::from("{'Venus': 0.7, 'Mars': 1.5, 'Mercury': 0.4, 'Earth': 1.0}");
println!("{:?}", x);

let solar_distance = HashMap::from(x);
println!("{:?}", solar_distance);
}

This fails with:

    |
7   | let solar_distance = HashMap::from(x);
    |                      ^^^^^^^^^^^^^ the trait `From<String>` is not implemented for `HashMap<_, _, _>`

So: since Rust already apparently has JSON dumps built in, has anyone written a JSON loads library?

CodePudding user response:

If you want to be able to initialize a HashMap concisely (similar to vec![]), take a look at https://crates.io/crates/hmap. It does basically exactly what you're describing.

If you want to work with serde_json, you can use the json!() macro provided by that library:

let x = json!({
  "foo": "bar",
  "baz": [1, 2, 3],
});
  • Related