Skip to content

HashMap atom keys and accessing atoms #693

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

Closed
samfrench opened this issue Apr 25, 2025 · 2 comments · Fixed by #695
Closed

HashMap atom keys and accessing atoms #693

samfrench opened this issue Apr 25, 2025 · 2 comments · Fixed by #695

Comments

@samfrench
Copy link

When I pass a Map to Rust it is fine if the keys are Strings or even if the keys and values are Terms.

#[rustler::nif]
fn call(opts: HashMap<String, String>) -> String {

Mostly I try to have the Rust library code with Rust types to let Rustler do the conversion. I have to use Term when the values could be any elixir term, which is probably what it is meant for.

I was wondering why Elixir would have Strings or Symbols as keys but Symbols are not supported as keys in the HashMap in Rust. Values seem to be fine if they are specified as Atoms.

#[rustler::nif]
fn call(opts: HashMap<Atom, String>) -> String {

Produces this:

the trait bound `rustler::Atom: Hash` is not satisfied
the trait `Decoder<'_>` is implemented for `HashMap<K, V>`
required for `HashMap<rustler::Atom, rustler::Term<'_>>` to implement `Decoder<'_>`

Maybe the keys should never be symbols in Rust, but if this is the case then was looking at the best way to convert. When using Term I can't find an easy way to get an item from the HashMap if wanting to do a string lookup. The best so far is to iterate through the items and convert all symbol keys to strings.

Would symbols as map keys be supported or is there a recommended approach for converting or looking up this type?

@scrogson
Copy link
Member

scrogson commented Apr 26, 2025

@samfrench I've put together a quick PR ( #694 ) which should fix the issue you're having. The error message you were getting was because Atom didn't implement Hash, so it couldn't be used as a key in a HashMap.

@samfrench
Copy link
Author

@scrogson thank you for that. I'll keep an eye on it. I did see #474 the other day which looks related. There was discussion on it for reasons why it might be more complex. Maybe that is different and it was from a few years ago.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants