Skip to content

ACP: hash_map! macro to create HashMaps such as vec! #578

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
stifskere opened this issue Apr 30, 2025 · 9 comments
Open

ACP: hash_map! macro to create HashMaps such as vec! #578

stifskere opened this issue Apr 30, 2025 · 9 comments
Labels
api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api

Comments

@stifskere
Copy link

Proposal

Add a hash_map! macro that would possibly generate a HashMap instead of using HashMap::from([]) which doesn't feel that idiomatic.

This isn't a performance addition, and wouldn't really change anything else more than add an idiomatic way of creating HashMaps.

Problem statement

Adding this macro would allow to make code cleaner, instead of having an iterable of tuples that is then collected to a HashMap we would have a more idiomatic macro at the style of vec! and this would possibly be an addition and motivation to make this for further structures.

Motivating examples or use cases

I made a library, which has templates, to fill these there is a HashMap<K: ToString, V: ToString> parameter, creating that is quite bulky for the user. The only way for it to not be bulky is to create that step by step, but sometimes this parameter will be simply a HashMap::from instantiation.

let translations = TestContext::load_translations(
    Language::ES,
    &HashMap::from([
        ("user", "John")
    ])
)

Solution sketch

The macro would look something along the lines of

hash_map!{
  "key" => "value",
  "key" => "value"
}

and this could directly generate a call to HashMap::from such as

macro_rules! hash_map {
    ($($key:expr => $value:expr),* $(,)?) => {{
        std::collections::HashMap::from([
            $(($key, $value)),*
        ])
    }}
}

Alternatives

This is too small to be made a crate, and re-implementing the macro on every project feels bulky.

Links and related work

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.
@stifskere stifskere added api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api labels Apr 30, 2025
@shepmaster
Copy link
Member

shepmaster commented Apr 30, 2025

See also rust-lang/rfcs#542

@stifskere
Copy link
Author

See also rust-lang/rfcs#542

Wouldn't this be part of the libs? should I keep this issue open or close it in favor of of that RFC?

@the8472
Copy link
Member

the8472 commented May 2, 2025

This is the right place, issues on the RFC repo only have limited significance.

@tgross35
Copy link

tgross35 commented May 2, 2025

I’ve seen a collection! macro proposed before that accepts either { key: value } syntax or [item, item, item]. It expands to either an array of k-v tuples or an array of items, and then calls .collect().

The type needs to be specified which is slightly less nice, but the upside is a single macro works for everything.

let hm: HashMap<_, _> = collection! { “foo”: 10, “bar”: 123 };
let bm: BTreeMap<_, _> = collection! { “foo”: 10, “bar”: 123 };
let hs: HashSet<_> = collection! { “foo, “bar”, “baz” };

// also custom types if they implement FromIter
let mm: MyMap<_> = collection! {};

// Some redundancy with vec!
let v: Vec<_> = collection![1, 2, 3];

@stifskere
Copy link
Author

I’ve seen a collection! macro proposed before that accepts either { key: value } syntax or [item, item, item]. It expands to either an array of k-v tuples or an array of items, and then calls .collect().

The type needs to be specified which is slightly less nice, but the upside is a single macro works for everything.

let hm: HashMap<_, > = collection! { “foo”: 10, “bar”: 123 };
let bm: BTreeMap<
, > = collection! { “foo”: 10, “bar”: 123 };
let hs: HashSet<
> = collection! { “foo, “bar”, “baz” };

// also custom types if they implement FromIter
let mm: MyMap<_> = collection! { … };

// Some redundancy with vec!
let v: Vec<_> = collection![1, 2, 3];

The pros of this is that if you are passing that invocation as argument or you are using a reference to it right after the type is inferred, and no problem after that.

The cons of this may be complexity on maintaining that macro, I don't know if rust works with the single principle practice but I feel it may be to complex. Another con I find is the redundancy of it, when you read code that you have never read and you see a function invocation, sometimes you may imagine what's up if you can read the arguments, but collection! may seem ambiguous in some cases.

@shepmaster
Copy link
Member

I’ve seen a collection! macro proposed before

See also rust-lang/rfcs#542 (comment)

@kennytm
Copy link
Member

kennytm commented May 3, 2025

Add a hash_map! macro that would possibly generate a HashMap instead of using HashMap::from([]) which doesn't feel that idiomatic.

Alternative, we just confirm HashMap::{from, from_iter} are idiomatic?

@stifskere
Copy link
Author

Add a hash_map! macro that would possibly generate a HashMap instead of using HashMap::from([]) which doesn't feel that idiomatic.

Alternative, we just confirm HashMap::{from, from_iter} are idiomatic?

It's not the from that I say is not idiomatic, it's the array of tuples that is not, In code you can just convert a HashMap to an array of Vector2 if you wanted, which is why I say it's not idiomatic.

@stifskere
Copy link
Author

I can open a draft pull request if necessary to integrate the macro. I'd like to contribute to rust in some way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api-change-proposal A proposal to add or alter unstable APIs in the standard libraries T-libs-api
Projects
None yet
Development

No branches or pull requests

5 participants